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

Plotly子图整合:如何将三类图表合并为单个Figure

用Plotly Subplots合并普通柱状图、堆叠柱状图和折线图

完全可以实现,核心是通过make_subplots创建多子图布局,分别添加不同类型的图表trace,其中堆叠柱状图需要为每个系列单独添加Bar trace并设置堆叠模式。

完整实现代码

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

# 初始化数据
data = pd.DataFrame([['A',0.25,0.25,0.25,0.25,125,0.032],
                     ['B',0.20,0.40,0.15,0.25,175,0.054],
                     ['C',0.25,0.25,0.30,0.20,192,0.065]])
data.columns = ['GROUP','Q1','Q2','Q3','Q4','SALES','IND']
data = data.set_index('GROUP')

# 创建3行1列的子图布局,添加子图标题
fig = make_subplots(rows=3, cols=1, 
                    subplot_titles=('普通柱状图(SALES)', '堆叠柱状图(Q1-Q4)', '折线图(IND)'))

# 1. 添加普通柱状图(第一行)
fig.add_trace(
    go.Bar(x=data.index, y=data['SALES'], text=data['SALES'], textposition='auto'),
    row=1, col=1
)

# 2. 添加堆叠柱状图(第二行)
# 为每个季度系列单独添加Bar trace,自动形成堆叠
for col in ['Q1', 'Q2', 'Q3', 'Q4']:
    fig.add_trace(
        go.Bar(x=data.index, y=data[col], name=col),
        row=2, col=1
    )
# 指定第二行的柱状图为堆叠模式
fig.update_layout(barmode='stack')

# 3. 添加折线图(第三行)
fig.add_trace(
    go.Scatter(x=data.index, y=data['IND'], mode='lines+markers', name='IND'),
    row=3, col=1
)

# 优化布局:调整高度、坐标轴标签,避免重叠
fig.update_layout(height=800, showlegend=False)
fig.update_xaxes(title_text='GROUP', row=1, col=1)
fig.update_xaxes(title_text='GROUP', row=2, col=1)
fig.update_xaxes(title_text='GROUP', row=3, col=1)
fig.update_yaxes(title_text='销售额', row=1, col=1)
fig.update_yaxes(title_text='季度比例', row=2, col=1)
fig.update_yaxes(title_text='IND指标', row=3, col=1)

fig.show()

关键说明

  • 堆叠柱状图实现:必须为每个需要堆叠的系列(Q1-Q4)单独添加go.Bar trace,且它们的x轴保持一致,最后通过barmode='stack'开启堆叠效果。
  • 子图定位:每个add_trace方法通过row和col参数指定该图表在子图布局中的位置。
  • 布局优化:通过update_layout和update_xaxes/update_yaxes调整图表高度、坐标轴标签,避免标题和元素重叠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 03:42:51