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

如何用Python的Altair创建堆叠柱状图?y表达式指定及数据格式疑问

Altair堆叠柱状图创建疑问与解决方案

核心问题

在以下示例中,要创建堆叠柱状图应指定什么y表达式?是否存在类似y="$all-other-columns"或y="$group-of-columns"的表达式?还是需要将数据重塑为**long-form(长格式)**以遵循官方示例及文档建议?

示例代码

import altair as alt
import pandas as pd

df = pd.DataFrame(
    [
        {'id_foo': 1, 'energy_carrier': 'oil', '2000': 5, '2020': 10},
        {'id_foo': 2, 'energy_carrier': 'electricity', '2000': 10, '2020': 20},
    ]
)

pivot_df = df.pivot_table(
    columns='energy_carrier',
    values=['2000', '2020'],
    aggfunc='sum',
)

plot_colors = ['blue', 'green']

plot_df = pivot_df.reset_index()

colors = alt.Color('energy_carrier:N', scale=alt.Scale(range=plot_colors))

chart = (
    alt.Chart(plot_df)
    .mark_bar()
    .encode(
        x='index:O',
        #y=?,
        color=colors,
    )
    .properties(width=200)
)

chart.show()

效果参考

预期效果:
预期效果

目标效果:
目标效果

相关问题(翻译)

如何在Altair中使用带索引的DataFrame?


解决方案

Altair没有$all-other-columns或$group-of-columns这类直接指定多列作为y轴的表达式,要创建堆叠柱状图,必须将数据转换为长格式(long-form),这也是Altair官方推荐的标准方式。

修改后的代码(直接处理原始数据)

import altair as alt
import pandas as pd

df = pd.DataFrame(
    [
        {'id_foo': 1, 'energy_carrier': 'oil', '2000': 5, '2020': 10},
        {'id_foo': 2, 'energy_carrier': 'electricity', '2000': 10, '2020': 20},
    ]
)

# 将宽格式数据转为长格式
long_df = df.melt(
    id_vars=['energy_carrier'],
    value_vars=['2000', '2020'],
    var_name='year',
    value_name='value'
)

plot_colors = ['blue', 'green']

chart = (
    alt.Chart(long_df)
    .mark_bar()
    .encode(
        x='year:O',
        y='value:Q',
        color=alt.Color('energy_carrier:N', scale=alt.Scale(range=plot_colors)),
        tooltip=['energy_carrier', 'year', 'value']  # 可选:添加交互提示
    )
    .properties(width=200)
)

chart.show()

基于原有plot_df的修改方案

如果要保留之前的plot_df处理流程,也可以对其做长格式转换:

# 处理已有的 plot_df 为长格式
long_plot_df = plot_df.melt(
    id_vars=['index'],
    var_name=['year', 'energy_carrier'],
    value_name='value'
)

chart = (
    alt.Chart(long_plot_df)
    .mark_bar()
    .encode(
        x='index:O',
        y='value:Q',
        color=alt.Color('energy_carrier:N', scale=alt.Scale(range=plot_colors)),
    )
    .properties(width=200)
)

chart.show()

说明

  • 长格式数据将原本分散在列中的年份信息转为行记录,让Altair能够识别分类维度(energy_carrier)和数值维度(value),自动实现柱状图的堆叠效果。
  • 转换后只需指定y='value:Q'作为数值轴,color区分不同能源类型即可完成堆叠配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 04:47:04