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

如何在多行多列子图的对应子图内放置各轨迹的图例

如何在多行多列子图的对应子图内放置各轨迹的图例

没问题!你想要把每个子图对应的轨迹图例放在各自子图内部,这个需求完全可以实现,咱们直接调整代码就能搞定,具体做法如下:

核心思路是关闭全局统一图例,然后为每个单独的轨迹指定图例的显示位置,让它刚好落在对应子图的内部区域。修改后的代码如下:

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

# 创建2行2列的子图,无需设置共享图例
fig = make_subplots(rows=2, cols=2, subplot_titles=("Plot 1", "Plot 2", "Plot 3", "Plot 4"))

# 给每个子图添加轨迹,并自定义图例位置到子图内部
# 子图1的图例放在自身右上角
fig.add_trace(go.Scatter(
    x=[1, 4, 1, 3, 5, 2], 
    y=[4, 5, 6, 5, 4, 2], 
    name="Trace 1",
    showlegend=True,
    legend=dict(x=0.45, y=0.95)  # 坐标是相对于整个画布的比例,0=最左/下,1=最右/上
), row=1, col=1)

# 子图2的图例放在自身右上角
fig.add_trace(go.Scatter(
    x=[1, 2, 3, 4, 3, 5], 
    y=[7, 8, 9, 3, 2, 6], 
    name="Trace 2",
    showlegend=True,
    legend=dict(x=0.95, y=0.95)
), row=1, col=2)

# 子图3的图例放在自身右上角
fig.add_trace(go.Scatter(
    x=[3, 5, 6, 4, 5, 6], 
    y=[1, 3, 5, 4, 2, 3], 
    name="Trace 3",
    showlegend=True,
    legend=dict(x=0.45, y=0.45)
), row=2, col=1)

# 子图4的图例放在自身右上角
fig.add_trace(go.Scatter(
    x=[1, 2, 3, 2, 6, 4], 
    y=[3, 4, 5, 6, 2, 1], 
    name="Trace 4",
    showlegend=True,
    legend=dict(x=0.95, y=0.45)
), row=2, col=2)

# 关闭全局默认的图例区域,避免重复显示
fig.update_layout(showlegend=False)

# 调整子图间距和布局,让图例显示更美观
fig.update_layout(
    margin=dict(l=50, r=50, t=50, b=50),
    grid=dict(rows=2, cols=2, pattern="independent")
)

# 展示图表
fig.show()

关键说明:

  • legend=dict(x=..., y=...):这里的x和y是相对于整个画布的比例值,范围从0到1,你可以根据自己的画布大小微调这些数值,让图例刚好落在子图的合适位置(比如左上角、右上角都可以);
  • showlegend=True:确保每个轨迹的图例单独显示;
  • fig.update_layout(showlegend=False):关闭全局统一的图例面板,避免出现重复的图例内容;
  • 最后调整margin和grid参数是为了让子图和图例的布局更协调,避免拥挤。

这样运行代码后,每个子图的右上角就会显示对应轨迹的图例,完全符合你的需求啦!

备注:内容来源于stack exchange,提问作者roudan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 07:10:30