I'm visualizing a dataset that has, for instance, a categorical field. I want to create a bar chart that shows the different categories for that field with their cardinality, sorted in 'ascendind'/'descending' order. This can simply be achieved with altair
:
import pandas as pd
import altair as alt
data = {0:{'Name':'Mary', 'Sport':'Tennis'},
1:{'Name':'Cal', 'Sport':'Tennis'},
2:{'Name':'John', 'Sport':'Tennis'},
3:{'Name':'Jane', 'Sport':'Tennis'},
4:{'Name':'Bob', 'Sport':'Golf'},
5:{'Name':'Jerry', 'Sport':'Golf'},
6:{'Name':'Gustavo', 'Sport':'Golf'},
7:{'Name':'Walter', 'Sport':'Swimming'},
8:{'Name':'Jessy', 'Sport':'Swimming'},
9:{'Name':'Patric', 'Sport':'Running'},
10:{'Name':'John', 'Sport':'Shooting'}}
df = pd.DataFrame(data).T
bars = alt.Chart(df).mark_bar().encode(
x=alt.X('count():Q', axis=alt.Axis(format='.0d', tickCount=4)),
y=alt.Y('Sport:N',
sort=alt.SortField(op='count', field='Sport:N', order='descending'))
)
bars
Now suppose I'm interested only in the first three most numerous categories. It seemed reasonable to use "transform_window" and “transform_filter” to filter the data but I was unable to find a way to do so. I also went to Vega-Lite Top K example trying to adapt it but without success (my "best" attempt is shown below).
bars.transform_window(window=[alt.WindowFieldDef(op='count',
field='Sport:N',
**{'as':'cardinality'})],
frame=[None, None])
bars.transform_window(window=[alt.WindowFieldDef(op='rank',
field='cardinality',
**{'as':'rank'})],
frame=[None, None],
sort=[alt.WindowSortField(field='rank',
order='descending')])
bars.transform_filter( ..... what??? .....)