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

Plotly使用make_subplots创建子图后如何显示图例?

解决Plotly双Y轴子图图例不显示问题

问题根源在于:用px.line生成的折线图合并到subfig后,部分trace的showlegend属性默认未启用,或图例名称未正确传递。以下是两种可行的解决方式:

方法1:手动开启每个trace的图例显示并指定名称

在添加trace后,直接为每个子图trace设置showlegend=True和自定义名称:

subfig = make_subplots(specs=[[{"secondary_y": True}]])

fig = px.line(dfa, y="revenue", template=template_style, markers=True)
fig2 = px.line(dfa, y="pdt_chg", template=template_style, markers=True)

fig2.update_traces(yaxis="y2")

subfig.add_traces(fig.data + fig2.data)
# 手动配置图例
subfig.data[0].update(name="Revenue", showlegend=True)
subfig.data[1].update(name="PDT Change", showlegend=True)

subfig.layout.title="Sales"
subfig.layout.xaxis.title="Year"
subfig.layout.yaxis.title="$"
subfig.layout.yaxis2.title="%"
subfig.update_layout(
    xaxis = dict(
        tickmode = 'linear',
        tick0 = 0,
        dtick = 1),  # 原dtick=0会导致刻度重叠,建议设为1
    title_x= 0.47,
    template=template_style)
subfig.for_each_trace(lambda t: t.update(line=dict(color=t.marker.color)))
subfig.show()

方法2:生成图表时直接指定名称,批量开启图例

在px.line中通过labels参数定义系列名称,再用for_each_trace批量开启图例:

subfig = make_subplots(specs=[[{"secondary_y": True}]])

# 生成图表时指定系列名称
fig = px.line(dfa, y="revenue", template=template_style, markers=True, labels={"revenue": "Revenue"})
fig2 = px.line(dfa, y="pdt_chg", template=template_style, markers=True, labels={"pdt_chg": "PDT Change"})

fig2.update_traces(yaxis="y2")

subfig.add_traces(fig.data + fig2.data)
# 批量开启所有trace的图例
subfig.for_each_trace(lambda t: t.update(showlegend=True))

subfig.layout.title="Sales"
subfig.layout.xaxis.title="Year"
subfig.layout.yaxis.title="$"
subfig.layout.yaxis2.title="%"
subfig.update_layout(
    xaxis = dict(
        tickmode = 'linear',
        tick0 = 0,
        dtick = 1),
    title_x= 0.47,
    template=template_style)
subfig.for_each_trace(lambda t: t.update(line=dict(color=t.marker.color)))
subfig.show()

注意:原代码中dtick=0会导致X轴刻度完全重叠,建议调整为合理间隔(如dtick=1)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 18:25:38