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

Plotly实现2行1列子图且保留柱状图堆叠效果的方法

如何用Plotly实现2行1列布局的堆叠柱状图+折线图

当使用Plotly子图功能创建2行1列的上下布局时,堆叠柱状图的堆叠效果消失,核心原因是未在布局中显式指定barmode='stack'——单图场景下的堆叠配置,在子图模式中同样需要声明,否则默认会使用分组模式(barmode='group')。

正确实现代码

import plotly.subplots as sp
import plotly.graph_objects as go

# 创建2行1列的子图网格,可添加子图标题
fig = sp.make_subplots(rows=2, cols=1, subplot_titles=("堆叠柱状图", "折线图"))

# 堆叠柱状图数据
categories = ['Category A', 'Category B', 'Category C']
values1 = [10, 20, 15]
values2 = [5, 15, 10]
values3 = [15, 10, 5]

# 将所有柱状图轨迹添加到第一行子图
fig.add_trace(go.Bar(x=categories, y=values1, name='Value 1'), row=1, col=1)
fig.add_trace(go.Bar(x=categories, y=values2, name='Value 2'), row=1, col=1)
fig.add_trace(go.Bar(x=categories, y=values3, name='Value 3'), row=1, col=1)

# 折线图数据
x_values = [1, 2, 3, 4, 5]
y_values = [3, 5, 8, 4, 9]

# 将折线图轨迹添加到第二行子图
fig.add_trace(go.Scatter(x=x_values, y=y_values, mode='lines+markers', name='Line Plot'), row=2, col=1)

# 更新全局布局:关键配置堆叠模式
fig.update_layout(
    title='堆叠柱状图与折线图(2行1列布局)',
    barmode='stack',  # 仅对同一子图内的柱状图生效
    height=700,  # 调整整体高度适配两行布局
    showlegend=True
)

# 为每个子图单独设置轴标题
fig.update_xaxes(title_text='分类', row=1, col=1)
fig.update_yaxes(title_text='数值', row=1, col=1)
fig.update_xaxes(title_text='X轴', row=2, col=1)
fig.update_yaxes(title_text='Y轴', row=2, col=1)

fig.show()

关键说明

  • barmode='stack'是堆叠效果的核心配置,只要多个柱状图轨迹属于同一个子图(此处为第一行第一列),该配置就会对其生效。
  • 使用update_xaxes/update_yaxes可以为不同子图设置独立的轴标题,避免全局配置导致的标题混乱。
  • subplot_titles参数可以为每个子图添加单独标题,提升图表可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 04:45:27