如何将分组条形图拆分为子组?Plotly子图实现问询
堆叠分组条形图实现(支持双日期系列)
数据集
| group | sub_group | value | date | |
|---|---|---|---|---|
| 0 | Animal | Cats | 12 | today |
| 1 | Animal | Dogs | 32 | today |
| 2 | Animal | Goats | 38 | today |
| 3 | Animal | Fish | 1 | today |
| 4 | Plant | Tree | 48 | today |
| 5 | Object | Car | 55 | today |
| 6 | Object | Garage | 61 | today |
| 7 | Object | Instrument | 57 | today |
| 8 | Animal | Cats | 44 | yesterday |
| 9 | Animal | Dogs | 12 | yesterday |
| 10 | Animal | Goats | 18 | yesterday |
| 11 | Animal | Fish | 9 | yesterday |
| 12 | Plant | Tree | 8 | yesterday |
| 13 | Object | Car | 12 | yesterday |
| 14 | Object | Garage | 37 | yesterday |
| 15 | Object | Instrument | 77 | yesterday |
需求说明
- 制作包含今日和昨日两个系列的条形图
- 每个系列内按
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
相关产品推荐
相关产品推荐

