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

如何用Plotly从同索引DataFrame创建带共享图例的子图?

实现共享联动图例的Plotly子图

要实现两个子图共享同一图例且点击图例可同步控制对应线条的显示,核心是利用Plotly的legendgroup参数将同一用户的线条归为一组,同时控制图例的显示逻辑。以下是完整解决方案:

完整代码

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

# 生成数据
df1 = pd.DataFrame({
    'user1':[1,1,2,3,3,4,5,1,1,1,4,4,4,5,6,6,6,6,3],
    'user2':[3,4,5,5,5,2,1,3,4,4,4,5,6,6,4,3,6,6,3],
    'user3':[1,5,2,3,4,5,2,2,1,1,1,2,3,4,5,5,4,4,2],
})

df2 = pd.DataFrame({
    'user1':[0,3,4,5,2,5,6,7,2,3,1,5,7,2,1,3,5,2,3],
    'user2':[3,3,4,5,6,7,2,1,3,1,3,5,6,7,2,2,2,3,9],
    'user3':[8,6,4,7,6,5,8,7,6,2,3,4,6,7,8,9,9,5,3],
})

# 创建2行1列的子图布局(可按需改为1行2列)
fig = make_subplots(rows=2, cols=1, subplot_titles=("PLOT 1", "PLOT 2"))

# 遍历用户列,为每个用户添加两个子图的线条并设置联动组
for user_col in df1.columns:
    # 添加df1的线条到第一个子图,显示图例项
    fig.add_trace(
        go.Scatter(x=df1.index, y=df1[user_col], name=user_col,
                   legendgroup=user_col, showlegend=True),
        row=1, col=1
    )
    # 添加df2的线条到第二个子图,不重复显示图例项,但归为同一联动组
    fig.add_trace(
        go.Scatter(x=df2.index, y=df2[user_col], name=user_col,
                   legendgroup=user_col, showlegend=False),
        row=2, col=1
    )

# 调整整体布局
fig.update_layout(
    height=800,
    width=800,
    title_text="共享联动图例的双折线子图",
    legend_title="用户分组"
)

fig.show()

关键说明

  • legendgroup参数:将同一用户在两个子图中的线条标记为同一组,点击图例时会同步显示/隐藏该组内的所有线条。
  • showlegend参数:仅让第一个子图的线条显示图例项,避免图例中出现重复的用户名称。
  • 若需要横向排列子图,只需将make_subplots的参数改为rows=1, cols=2,并对应修改add_trace中的row和col值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 14:54:24