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

如何合并Plotly图例?将颜色与符号图例合并为单个图例

合并Plotly中Color与Symbol图例为单个分类图例

问题背景

当前使用Plotly Express绘制散点图时,同时通过color和symbol参数绑定了同一个subtype变量,导致图例中每个分类重复显示两次(分别对应color和symbol),希望将其合并为以「subtype」为标题、每个分类只显示一次的图例。

解决方案

核心思路是统一每个分类的图例组(legendgroup),仅保留每组中的一个图例条目,同时修改图例标题。具体实现如下:

修改后的完整代码

import pandas as pd 
import plotly.express as px
import numpy as np
from sklearn.decomposition import PCA

pca = PCA()
X_pca = pca.fit_transform(X)

fig = px.scatter(X_pca, x=0, y=1, color=df["subtype"], width=600, height=600, 
                 color_discrete_sequence=["red", "orange", "brown", "green"], 
                 title="Kernel PCA - tumor subtype vs normal", 
                 symbol=df["subtype"], 
                 symbol_sequence=['circle', 'circle', 'circle', 'square'])

# 合并图例的核心逻辑
seen_groups = set()
for trace in fig.data:
    # 提取分类名称(剔除Plotly自动添加的", color"/", symbol"后缀)
    group_name = trace.name.split(',')[0].strip()
    trace.legendgroup = group_name
    if group_name not in seen_groups:
        seen_groups.add(group_name)
        trace.name = group_name  # 重命名trace为纯分类名称
    else:
        trace.showlegend = False

# 原有可视化配置保留
fig.update_traces(marker=dict(size=5, line=dict(width=0.5, color='DarkSlateGrey')), selector=dict(mode='markers'))
fig.update_xaxes(automargin=True)
fig.update_yaxes(automargin=True)
fig.update_layout(
    plot_bgcolor='rgb(240,240,240)', 
    paper_bgcolor='rgb(240,240,240)',
    legend_title_text='subtype'  # 设置统一的图例标题
)

fig.show()
fig.write_image("meth_subtype_pca.png")

关键代码说明

  • seen_groups集合用于跟踪已处理的分类,确保每个分类仅保留一个图例条目
  • 通过split(',')[0].strip()清理Plotly自动生成的带后缀的trace名称
  • 统一设置legendgroup后,点击图例时会同步控制该分类下所有点的显示/隐藏
  • legend_title_text参数将图例标题改为目标的「subtype」

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 09:45:49