I'm visualizing a dataset that has, for instance, a categorical field and a temporal field. I want to create a strip chart that shows the temporal distribution of the different categories sorted in 'ascending'/'descending' order depending on their cardinality. This can simply be achieved with altair:
import pandas as pd
import altair as alt
data = {0:{'Name':'Mary', 'Sport':'Tennis', 'competition':'2018/06/01'},
1:{'Name':'Cal', 'Sport':'Tennis','competition':'2018/06/05'},
2:{'Name':'John', 'Sport':'Tennis','competition':'2018/05/28'},
3:{'Name':'Jane', 'Sport':'Tennis','competition':'2018/05/20'},
4:{'Name':'Bob', 'Sport':'Golf','competition':'2018/03/01'},
5:{'Name':'Jerry', 'Sport':'Golf','competition':'2018/03/03'},
6:{'Name':'Gustavo', 'Sport':'Golf','competition':'2018/02/28'},
7:{'Name':'Walter', 'Sport':'Swimming','competition':'2018/01/01'},
8:{'Name':'Jessy', 'Sport':'Swimming','competition':'2018/01/03'},
9:{'Name':'Patric', 'Sport':'Running','competition':'2018/02/01'},
10:{'Name':'John', 'Sport':'Shooting','competition':'2018/04/01'}}
df = pd.DataFrame(data).T
alt.Chart(df).mark_tick().encode(
x='yearmonthdate(competition):T',
y=alt.Y('Sport:N',
sort=alt.SortField(field='count(Sport:N)', order='ascending', op='sum')
),
)
Now suppose I'm interested only in the first three most numerous categories. Following the accepted solution for "Altair/Vega-Lite bar chart: filter top K bars from aggregated field", this time the plot does't show up:
alt.Chart(df).mark_tick().encode(
x='yearmonthdate(competition):T',
y=alt.Y('Sport:N',
sort=alt.SortField(field='count', order='ascending', op='sum')
),
).transform_aggregate(
count='count()',
groupby=['Sport']
).transform_window(
window=[{'op': 'rank', 'as': 'rank'}],
sort=[{'field': 'count', 'order': 'descending'}]
).transform_filter('datum.rank <= 3')
Notice that even the y-labels order isn't as expected.


