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

Plotly中如何将fig2设为fig1的子图?代码报错求助

问题解决方法

错误原因

make_subplots的add_trace方法要求传入单个绘图轨迹(trace)对象,但你直接传入了Plotly Express生成的完整Figure对象(fig1、fig2),导致参数类型不匹配,触发错误。另外代码里的中文引号‘Overnight’会引发语法错误,需要替换为英文引号。

修正步骤

  • 从Plotly Express生成的Figure对象中提取trace:每个px.xxx()生成的fig,其绘图轨迹存储在fig.data列表中,取第一个元素即可(你的场景中每个fig只对应一个trace)。
  • 将中文引号替换为英文引号,避免语法错误。

修正后的完整代码

from plotly.subplots import make_subplots
import plotly.graph_objects as go
import plotly.express as px  # 补充导入px,原代码遗漏该行

fig1 = px.area(CPI_and_Interest, x=CPI_and_Interest.index, y='Chi_so')
fig2 = px.line(CPI_and_Interest, x=CPI_and_Interest.index, y=['Overnight'])

fig = make_subplots(rows=2, cols=1,
                    shared_xaxes=True,
                    vertical_spacing=0.02)

# 提取trace并添加到子图
fig.add_trace(fig1.data[0], row=1, col=1)
fig.add_trace(fig2.data[0], row=2, col=1)

# 可选:保留原绘图的轴标签、标题等样式
fig.update_layout(fig1.layout)
fig.update_xaxes(title_text=fig1.layout.xaxis.title.text, row=1, col=1)
fig.update_xaxes(title_text=fig2.layout.xaxis.title.text, row=2, col=1)
fig.update_yaxes(title_text=fig1.layout.yaxis.title.text, row=1, col=1)
fig.update_yaxes(title_text=fig2.layout.yaxis.title.text, row=2, col=1)

fig.show()

关键说明

  • fig1.data[0]获取面积图的trace对象,fig2.data[0]获取折线图的trace对象,这才是add_trace能接受的参数类型。
  • 补充import plotly.express as px,否则会因找不到px模块报错。
  • 可选的布局更新代码可以保留原Plotly Express绘图的样式,让子图更符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 20:25:11