调整Altair直方图中分类列的显示顺序
调整Altair直方图中分类列的顺序
要自定义Altair直方图里分类列的顺序,有两种实用方法:
方法1:在Altair编码中直接指定排序规则
在alt.X()配置里添加sort参数,传入你需要的分类顺序列表即可:
import pandas as pd import altair as alt data = {'Age group': {0: '0 - 4', 1: '12 - 16', 2: '5 - 11', 3: 'not specified'}, 'Count': {0: 81.0, 1: 86.0, 2: 175.0, 3: 0.0}} dp = pd.DataFrame(data) alt.Chart(dp).mark_bar().encode( x=alt.X('Age group:N', title='Age group', sort=['0 - 4', '5 - 11', '12 - 16', 'not specified']), y='Count:Q', tooltip=['Age group', 'Count'] ).properties(title='Number of children in voucher', width=400)
方法2:将列转换为pandas分类类型
先把Age group列设置为带指定顺序的分类类型,Altair会自动识别并沿用这个顺序:
import pandas as pd import altair as alt data = {'Age group': {0: '0 - 4', 1: '12 - 16', 2: '5 - 11', 3: 'not specified'}, 'Count': {0: 81.0, 1: 86.0, 2: 175.0, 3: 0.0}} dp = pd.DataFrame(data) # 定义分类顺序 age_order = ['0 - 4', '5 - 11', '12 - 16', 'not specified'] dp['Age group'] = pd.Categorical(dp['Age group'], categories=age_order, ordered=True) alt.Chart(dp).mark_bar().encode( x=alt.X('Age group:N', title='Age group'), y='Count:Q', tooltip=['Age group', 'Count'] ).properties(title='Number of children in voucher', width=400)
两种方法都能让直方图的列按需求排列,可根据你的数据处理习惯选择。
内容的提问来源于stack exchange,提问作者elksie5000
相关产品推荐
相关产品推荐

