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

如何在Streamlit中创建分组条形图?解决st.altair生成堆叠图问题

在Streamlit中实现Altair分组条形图的解决方案

要解决Altair生成堆叠条形图而非分组条形图的问题,核心是在条形图标记中指定并列模式,同时确保数据格式适配分组展示。

关键步骤与代码示例

  1. 确保数据为长格式(每个类别-系列组合对应一行数据),这是Altair处理分组图表的基础。
  2. 在mark_bar()中添加position='dodge'参数,强制条形图并列显示而非堆叠。

完整代码示例:

import streamlit as st
import altair as alt
import pandas as pd

# 构造长格式示例数据
data = pd.DataFrame({
    "类别": ["A", "A", "B", "B", "C", "C"],
    "系列": ["系列1", "系列2", "系列1", "系列2", "系列1", "系列2"],
    "数值": [10, 15, 20, 25, 12, 18]
})

# 构建分组条形图
chart = alt.Chart(data).mark_bar(position='dodge').encode(
    x=alt.X('类别:N', title='类别'),
    y=alt.Y('数值:Q', title='数值'),
    color=alt.Color('系列:N', title='系列'),
    tooltip=['类别', '系列', '数值']
).properties(
    title='分组条形图示例'
)

# 在Streamlit中渲染图表
st.altair_chart(chart, use_container_width=True)

宽格式数据适配

如果你的数据是宽格式(每个系列作为单独列),需要先通过transform_fold转换为长格式:

# 宽格式数据示例
wide_data = pd.DataFrame({
    "类别": ["A", "B", "C"],
    "系列1": [10, 20, 12],
    "系列2": [15, 25, 18]
})

chart = alt.Chart(wide_data).transform_fold(
    ['系列1', '系列2'],  # 指定要转换的列
    as_=['系列', '数值']
).mark_bar(position='dodge').encode(
    x='类别:N',
    y='数值:Q',
    color='系列:N'
)

st.altair_chart(chart, use_container_width=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:55:36