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

合并左右双Y轴Plotly图表时右轴消失的解决方法

右侧Y轴消失的原因及解决方法

嘿,我来帮你捋清楚这个问题:

为啥合并后右侧Y轴没了?

当你直接用fig1.data + fig2.data合并两个图的轨迹时,只把数据部分拼在了一起,但两个图的布局配置(比如Y轴的位置、绑定关系)并没有被同步过来。Plotly的图表是由data(轨迹数据)和layout(布局设置)两部分组成的,你之前给fig2设置的右侧Y轴属于layout里的配置,直接合并data根本带不动这部分,所以默认只会显示左侧的主Y轴。

另外还有个关键点:你没给第二个散点图的轨迹明确指定要绑定到右侧Y轴(也就是yaxis="y2"),所以它默认会用主Y轴,自然右侧轴就没机会显示啦。

正确的合并姿势

下面给你两种靠谱的方案,都能完美保留左右Y轴:

方案1:基于已有图的布局,添加轨迹并配置右侧轴

import plotly.express as px
import plotly.graph_objects as go

# 第一个图:左侧Y轴
fig1 = px.scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16])
fig1.update_traces(marker=dict(
            color='red',
            size=20,
            line=dict(
                color='MediumPurple',
                width=2
            )
        ))
fig1.update_yaxes(side="left")

# 第二个图:右侧Y轴的轨迹数据
fig2 = px.scatter(x=[0, 1, 2, 3, 4], y=[0, 2, 8, 18, 32])
fig2.update_traces(marker=dict(
            color='blue',
            size=20,
            line=dict(
                color='MediumPurple',
                width=2
            )
        ))

# 以fig1的布局为基础创建新图
go_fig = go.Figure(data=fig1.data)

# 添加fig2的轨迹到新图
go_fig.add_trace(fig2.data[0])

# 配置右侧Y轴:设置位置、叠加主Y轴,还能加标题区分
go_fig.update_layout(
    yaxis=dict(title_text="左侧Y轴"),  # 给左侧轴加标题(可选)
    yaxis2=dict(
        side="right",
        overlaying="y",
        title_text="右侧Y轴"
    )
)

# 给第二个轨迹明确指定绑定到右侧Y轴
go_fig.data[1].update(yaxis="y2")

go_fig.show()

方案2:手动合并data和layout的完整配置

import plotly.express as px
import plotly.graph_objects as go

fig1 = px.scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16])
fig1.update_traces(marker=dict(color='red', size=20, line=dict(color='MediumPurple', width=2)))
fig1.update_yaxes(side="left")

fig2 = px.scatter(x=[0, 1, 2, 3, 4], y=[0, 2, 8, 18, 32])
fig2.update_traces(marker=dict(color='blue', size=20, line=dict(color='MediumPurple', width=2)))
# 提前给fig2的Y轴设置叠加属性,这样它的layout会包含y2的配置
fig2.update_yaxes(side="right", overlaying="y")

# 同时合并data和layout
go_fig = go.Figure(
    data=fig1.data + fig2.data,
    layout=go.Layout(
        yaxis=fig1.layout.yaxis,
        yaxis2=fig2.layout.yaxis,
        xaxis=fig1.layout.xaxis  # 复用x轴的配置
    )
)

# 确保第二个轨迹绑定到y2轴
go_fig.data[1].yaxis = "y2"

go_fig.show()

划重点

  • 合并图表时不能只拼data,必须同步处理layout里的轴配置
  • 每个轨迹都要明确指定对应的Y轴(yaxis="y"是左侧主轴,yaxis="y2"是右侧副轴)
  • 右侧Y轴一定要设置overlaying="y",这样才能和左侧轴在同一个绘图区域显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 10:16:36