我正在可视化具有例如分类字段和时间字段的数据集。我想创建一个条形图,显示不同类别的时间分布,根据它们的基数按“升序”/“降序”顺序排序。这可以通过以下方式简单地实现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')
),
)
现在假设我只对前三个数量最多的类别感兴趣。遵循“ Altair/Vega-Lite bar chart: filter top K bars from aggregated field ”的公认解决方案,这次绘图没有显示:
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')
请注意,即使是 y-labels 顺序也不如预期。