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

基于Pandas DataFrame的Plotly子图图例交互问题求助

解决Plotly多子图图例联动与分组问题

核心原理

要实现跨子图的图例联动,必须给同一图例控制的所有轨迹设置相同的legendgroup参数,且仅保留其中一个轨迹的showlegend=True,其余设为False。这样点击图例时,同组的所有轨迹会同步显示/隐藏。


处理Y轴列A的单图例联动

实现步骤

  • 提取列M的所有离散唯一值
  • 创建3个子图布局(对应K、L、M三个X轴)
  • 遍历每个M值,为每个子图添加对应轨迹,统一设置legendgroup为M值,仅在第一个子图的轨迹开启showlegend

代码示例

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

# 构造示例DataFrame
np.random.seed(42)
df = pd.DataFrame({
    'A': np.random.rand(30),
    'B': np.random.rand(30),
    'K': np.arange(30),
    'L': np.arange(30)*0.5,
    'M': np.repeat(['M1', 'M2', 'M3'], 10),
    'label': np.repeat(['label1', 'label2'], 15)
})

# 绘制Y轴A的Figure
fig_a = make_subplots(rows=1, cols=3, subplot_titles=('A vs K', 'A vs L', 'A vs M'))
m_unique = df['M'].unique()
x_cols = ['K', 'L', 'M']

for m_val in m_unique:
    df_m = df[df['M'] == m_val]
    for col_idx, x_col in enumerate(x_cols, 1):
        show_leg = (col_idx == 1)
        fig_a.add_trace(
            go.Scatter(
                x=df_m[x_col],
                y=df_m['A'],
                mode='markers',
                name=m_val,
                legendgroup=m_val,
                showlegend=show_leg,
                marker=dict(color=dict(M1='red', M2='blue', M3='green')[m_val])
            ),
            row=1, col=col_idx
        )

fig_a.update_layout(title='Y轴A的联动图例', height=400)
fig_a.show()

处理Y轴列B的分组图例联动

实现步骤

  • 按label和M的组合创建图例组(legendgroup=f"{label}_{m_val}")
  • 用legendgrouptitle参数设置分组标题(对应label值)
  • 仅在第一个子图的对应轨迹开启showlegend,确保每个图例组只显示一次

代码示例

# 绘制Y轴B的Figure
fig_b = make_subplots(rows=1, cols=3, subplot_titles=('B vs K', 'B vs L', 'B vs M'))

# 定义标记样式字典
marker_style = {
    'label1': dict(symbol='circle', size=8),
    'label2': dict(symbol='square', size=8)
}
label_m_pairs = df[['label', 'M']].drop_duplicates().values.tolist()

for label, m_val in label_m_pairs:
    df_label_m = df[(df['label'] == label) & (df['M'] == m_val)]
    for col_idx, x_col in enumerate(x_cols, 1):
        show_leg = (col_idx == 1)
        fig_b.add_trace(
            go.Scatter(
                x=df_label_m[x_col],
                y=df_label_m['B'],
                mode='markers',
                name=m_val,
                legendgroup=f"{label}_{m_val}",
                legendgrouptitle=dict(text=label),
                showlegend=show_leg,
                marker={**marker_style[label], 'color': dict(M1='red', M2='blue', M3='green')[m_val]}
            ),
            row=1, col=col_idx
        )

fig_b.update_layout(title='Y轴B的分组联动图例', height=400)
fig_b.show()

关键注意事项

  • legendgroup必须完全匹配,大小写、符号都不能错,否则无法联动
  • 每个legendgroup只能有一个轨迹设置showlegend=True,避免图例重复
  • 分组图例中,点击legendgrouptitle可以一键切换整组轨迹的显示状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 19:52:49