Altair绘制学术职称性别金字塔图时数据错位问题排查
问题根因
数据错位是因为仅中间文本图层配置了学术层级的排序规则,左右两个条形图层的Y轴未指定相同排序逻辑。
Altair中标记为:O的序数类型字段,默认按字段值字母顺序/数据集内首次出现顺序排布,三个图层独立计算Y轴类别位置,就会出现类别对应错位、数据互换的问题。
修复方法
给左、中、右三个图层的y轴编码配置完全一致的排序规则即可,不要只在中间文本层加sort参数。推荐把排序规则抽为公共常量,避免重复配置出错。
修复后的可运行代码:
import altair as alt import pandas as pd # 统一定义学术职能层级从上到下的显示顺序 LEVEL_SORT = ['Professor', 'Associate Professor', 'Assistant Professor', 'Postdoc', 'PhD'] df_natuur_vrouw = df_natuur[df_natuur['geslacht'] == 'V'] df_natuur_man = df_natuur[df_natuur['geslacht'] == 'M'] slider = alt.binding_range(min=2011, max=2020, step=1) select_year = alt.selection_single(name='year', fields=['year'], bind=slider, init={'year': 2020}) base_vrouw = alt.Chart(df_natuur_vrouw).add_selection( select_year ).transform_filter( select_year ).properties( width=250 ) base_man = alt.Chart(df_natuur_man).add_selection( select_year ).transform_filter( select_year ).properties( width=250 ) color_scale = alt.Scale(domain=['M', 'V'], range=['#003865', '#ee7203']) # 左侧女性柱形:Y轴绑定统一排序规则 left = base_vrouw.encode( y=alt.Y('functieniveau:O', axis=None, sort=LEVEL_SORT), x=alt.X('percentage_afgerond:Q', title='percentage', scale=alt.Scale(domain=[0, 100], reverse=True)), color=alt.Color('geslacht:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Female') # 中间层级文本:复用相同排序规则 middle = base_vrouw.encode( y=alt.Y('functieniveau:O', axis=None, sort=LEVEL_SORT), text=alt.Text('functieniveau:O'), ).mark_text().properties(width=110) # 右侧男性柱形:Y轴绑定统一排序规则 right = base_man.encode( y=alt.Y('functieniveau:O', axis=None, sort=LEVEL_SORT), x=alt.X('percentage_afgerond:Q', title='percentage', scale=alt.Scale(domain=[0, 100])), color=alt.Color('geslacht:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Male') alt.concat(left, middle, right, spacing=5, title='Percentage male and female employees per academic level in nature sector 2011-2020')
优化提示
如果后续需要切换自然、技术领域的数据集,不要拆分男女单独生成子数据集,直接基于原始全量数据集做过滤即可,能从根源上避免多数据源排序不一致的问题。
内容的提问来源于stack exchange,提问作者Marlieke
相关产品推荐
相关产品推荐

