You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Altair归一化堆叠柱状图添加“占总量百分比”文本标签

为Altair归一化堆叠柱状图添加分段百分比标签实现方案
  • 核心逻辑:通过图层叠加的方式,在原有柱状图基础上增加独立的文本标记图层,保证文本和柱段完全对齐,避免位置错位
  • 对齐规则:文本图层必须和柱状图层保持完全一致的x轴维度、y轴堆叠规则、颜色映射关系、交互选中逻辑,否则会出现文本和柱段不匹配的问题
  • 显示配置:直接复用已经计算好的PercentOfTotal字段作为文本内容,设置百分比格式化规则,搭配合适的字体颜色、位置偏移提升可读性

修改后可直接运行的完整代码

# 保留原有图例多选交互逻辑
legend_selection = alt.selection_multi(fields=['status'], bind='legend')

# 抽离公共数据变换逻辑,减少重复代码
base = alt.Chart(selected_publication_total_subs_df).transform_joinaggregate(
    TotalSubCnt='sum(subscriber_cnt)'
).transform_calculate(
    PercentOfTotal='datum.subscriber_cnt / datum.TotalSubCnt'
)

# 构建原有柱状图层
bar = base.mark_bar().encode(
    x=alt.X('yearmonthdate(as_of_date):O', axis=alt.Axis(title='', labelFontSize=12, labelPadding=10, labelAngle=-45)),
    y=alt.Y(
        'sum(subscriber_cnt)', 
        stack='normalize', 
        axis=alt.Axis(format='%', title='% of Subscriber Count' ,labelFontSize=12, labelPadding=10, titleFontSize=16, titlePadding=20)
    ),
    color=alt.Color('status'),
    opacity=alt.condition(legend_selection, alt.value(1), alt.value(0.1))
).properties(width=1000,height=400).add_selection(legend_selection)

# 构建和柱段完全对齐的文本标签图层
text = base.mark_text(
    fontSize=12,
    color='white',
    baseline='middle'
).encode(
    x=alt.X('yearmonthdate(as_of_date):O'),
    y=alt.Y('sum(subscriber_cnt):Q', stack='normalize'),
    text=alt.Text('PercentOfTotal:Q', format='.1%'),
    color=alt.Color('status', legend=None), # 取消文本图层的图例,避免和柱状图图例重复
    opacity=alt.condition(legend_selection, alt.value(1), alt.value(0.1))
)

# 叠加两个图层生成最终图表
bar = bar + text

适配调整说明

  • 针对占比过低的柱段出现的文本重叠问题,可以在transform_calculate中增加判断逻辑,当PercentOfTotal < 0.02时将文本设为空值,不显示对应标签
  • 可通过mark_text的dy参数微调文本的垂直偏移位置,进一步优化视觉效果
  • 如果需要显示整数百分比,只需将format='.1%'调整为format='.0%'即可

内容的提问来源于stack exchange,提问作者msquaredsa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 13:15:03