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

如何将分组条形图拆分为子组?Plotly子图实现问询

堆叠分组条形图实现(支持双日期系列)

数据集

groupsub_groupvaluedate
0AnimalCats12today
1AnimalDogs32today
2AnimalGoats38today
3AnimalFish1today
4PlantTree48today
5ObjectCar55today
6ObjectGarage61today
7ObjectInstrument57today
8AnimalCats44yesterday
9AnimalDogs12yesterday
10AnimalGoats18yesterday
11AnimalFish9yesterday
12PlantTree8yesterday
13ObjectCar12yesterday
14ObjectGarage37yesterday
15ObjectInstrument77yesterday

需求说明

  • 制作包含今日和昨日两个系列的条形图
  • 每个系列内按group划分条形,每个group的条形由对应sub_group堆叠(比如「Animal - today」条形由猫、狗、山羊、鱼的数值堆叠,总值为83)
  • 图表需支持添加到subplot子图中,效果参考Plotly长格式数据条形图的样式

用户尝试的代码

fig = make_subplots(rows = 1, cols = 1)

fig.add_trace(go.Bar(
            y = df[df['date'] == 'today']['amount'],
            x = df[df['date'] == 'today']['group'],
            color = df[df['date'] == 'today']['sub_group']
        ),
    row = 1, col = 1
)

fig.add_trace(go.Bar(
            y = df[df['date'] == 'yesterday']['amount'],
            x = df[df['date'] == 'yesterday']['group'],
            color = df[df['date'] == 'yesterday']['sub_group']
        ),
    row = 1, col = 1
)

fig.show()

问题修正与可行代码

原代码存在三个核心问题:数据集列名是value但代码用了amount、go.Bar无color参数、未设置堆叠逻辑。以下是修正后的完整代码:

import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd

# 构造数据集(已有df可跳过此段)
data = [
    ["Animal", "Cats", 12, "today"],
    ["Animal", "Dogs", 32, "today"],
    ["Animal", "Goats", 38, "today"],
    ["Animal", "Fish", 1, "today"],
    ["Plant", "Tree", 48, "today"],
    ["Object", "Car", 55, "today"],
    ["Object", "Garage", 61, "today"],
    ["Object", "Instrument", 57, "today"],
    ["Animal", "Cats", 44, "yesterday"],
    ["Animal", "Dogs", 12, "yesterday"],
    ["Animal", "Goats", 18, "yesterday"],
    ["Animal", "Fish", 9, "yesterday"],
    ["Plant", "Tree", 8, "yesterday"],
    ["Object", "Car", 12, "yesterday"],
    ["Object", "Garage", 37, "yesterday"],
    ["Object", "Instrument", 77, "yesterday"],
]
df = pd.DataFrame(data, columns=["group", "sub_group", "value", "date"])

# 创建子图
fig = make_subplots(rows=1, cols=1)

# 获取唯一的子组和日期值
sub_groups = df["sub_group"].unique()
dates = df["date"].unique()

# 遍历日期和子组,添加堆叠条形轨迹
for date in dates:
    for sub in sub_groups:
        filtered_data = df[(df["date"] == date) & (df["sub_group"] == sub)]
        fig.add_trace(
            go.Bar(
                x=filtered_data["group"],
                y=filtered_data["value"],
                name=f"{sub} - {date}",
                legendgroup=f"{sub}",  # 同子组分入同一图例组
                showlegend=(date == dates[0]),  # 仅首次显示图例,避免重复
            ),
            row=1, col=1
        )

# 开启堆叠模式
fig.update_layout(barmode="stack")

fig.show()

代码说明

  • 遍历每个日期和子组,为每个组合创建独立的Bar轨迹,确保同group下的子组能堆叠
  • 用legendgroup将同一子组的不同日期轨迹归为一组,优化图例显示
  • 通过showlegend控制图例只显示一次,避免冗余
  • 调用update_layout(barmode="stack")开启堆叠条形模式
  • 代码兼容subplot布局,可直接嵌入多行列的子图中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:20:24