You need to enable JavaScript to run this app. Altair 归一化堆叠条形图添加占比标签及修复标签对齐问题
优惠活动
大模型
产品
解决方案
定价
更多

Altair 归一化堆叠条形图添加占比标签及修复标签对齐问题

Altair 归一化堆叠条形图标签对齐问题

问题背景

我使用Altair绘制堆叠条形图,初始代码如下,实现了按计数展示的堆叠条形图,每个颜色分段显示对应计数值:

import altair as alt
from vega_datasets import data

# get iris dataset and take 120 observations from it
source = data.iris()[10:130]
# add one more feature to dataset
colors = ['red', 'orange', 'blue', 'red'] * 30
source['colors'] = colors

chart = alt.Chart(source).mark_bar().encode(
    alt.Y('species:N', sort='x'),
    alt.X('count():Q', stack='zero'),
    color=alt.Color('colors', sort=colors), 
    order="colors",
    
)

text = alt.Chart(source).mark_text(dx=-7, dy=3, color='white')\
    .encode(
    alt.Y("species:N", sort='x'),
    alt.X('count():Q', stack="zero"),
    order="colors",
    text=alt.Text('count():Q')
    )

chart + text

输出为显示每个'color'特征计数标签的条形图
我希望将该图表转为归一化堆叠模式,标签对应展示分段占整体的比例,调整后代码如下:

import altair as alt
from vega_datasets import data

source = data.iris()[10:130]
colors = ['red', 'orange', 'blue', 'red'] * 30
source['colors'] = colors


chart = alt.Chart(source).mark_bar().encode(
    alt.Y('species:N', sort='x'),
    alt.X('count():Q', stack='normalize'),
    color=alt.Color('colors', sort=colors), 
    order="colors",
    
)

text = alt.Chart(source).mark_text(dx=-7, dy=3, color='white')\
    .encode(
    alt.Y("species:N", sort='x'),
    alt.X('count():Q', stack="normalize"),
    order="colors",
    text=alt.Text('count():Q')
    )

chart + text

归一化条形图
此时标签仍显示计数值,我期望第一个条形的标签从8、7、15替换为保留两位小数的0.27、0.23、0.5这类占比值。我后续做了如下调整:
更新
我目前的实现代码如下:

import altair as alt
from vega_datasets import data

source = data.iris()[10:130]
colors = ['red', 'orange', 'blue', 'red'] * 30
sort_order=['blue', 'orange', 'red']
source['colors'] = colors

chart = alt.Chart(source).mark_bar().encode(
    alt.Y('species:N', sort='x'),
    alt.X('count():Q', stack='normalize'),
    color=alt.Color('colors', sort=sort_order), 
    order = 'colors'
)

text = alt.Chart(source).transform_aggregate(count='count()', groupby=['species', 'colors'])\
    .transform_joinaggregate(total='sum(count)', groupby=["species"])\
    .transform_calculate(frac=alt.datum.count / alt.datum.total)\
    .mark_text(align='right', dx=-7, dy=3, color='white')\
    .encode(
    alt.Y("species:N", sort='x'),
    alt.X('count():Q', stack="normalize"),
    text=alt.Text('frac:Q', format='.0%'),
    order = 'colors'
    )

chart + text

调整后效果图
但此时标签对齐异常,我需要让标签和前两个示例一样,定位在每个颜色分段的末端位置,请问该如何修复该对齐问题?

解决方案

问题原因

标签错位的核心原因是:你已经对text图层的数据做了transform_aggregate聚合,此时每个species + colors分组仅剩下1行数据,你再用count():Q做X轴映射时,返回的计数值都是1,和实际的分组计数不匹配,自然无法和条形的堆叠位置对齐。

修复代码

只需要把text图层的X轴映射从count():Q改成我们提前聚合好的sum(count):Q即可,完整修正代码如下:

import altair as alt
from vega_datasets import data

source = data.iris()[10:130]
colors = ['red', 'orange', 'blue', 'red'] * 30
sort_order=['blue', 'orange', 'red']
source['colors'] = colors

chart = alt.Chart(source).mark_bar().encode(
    alt.Y('species:N', sort='x'),
    alt.X('count():Q', stack='normalize'),
    color=alt.Color('colors', sort=sort_order), 
    order = 'colors'
)

text = alt.Chart(source).transform_aggregate(count='count()', groupby=['species', 'colors'])\
    .transform_joinaggregate(total='sum(count)', groupby=["species"])\
    .transform_calculate(frac=alt.datum.count / alt.datum.total)\
    .mark_text(align='right', dx=-7, dy=3, color='white')\
    .encode(
    alt.Y("species:N", sort='x'),
    # 这里修改为sum(count),用提前聚合好的分组计数做堆叠,和条形层逻辑一致
    alt.X('sum(count):Q', stack="normalize"),
    # 如果要显示0.27这类小数,就把format改成'.2f'
    text=alt.Text('frac:Q', format='.0%'),
    order = 'colors'
    )

chart + text

格式调整说明

如果你不需要百分比格式,想要显示0.27、0.23这类两位小数的占比,只需要把text=alt.Text('frac:Q', format='.0%')改成text=alt.Text('frac:Q', format='.2f')即可。

内容的提问来源于stack exchange,提问作者Андрій zOFsky

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 19:03:02