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

Matplotlib 3.10+版本下如何隐藏指定图例标签?

解决Seaborn图表选择性显示图例标签的问题

Matplotlib 3.10+移除了用下划线隐藏图例标签的特性后,你可以通过以下几种方法实现Seaborn图表的图例选择性显示:

方法1:筛选现有图例条目

先获取Seaborn绘图后生成的图例句柄和标签,只保留你需要的部分,再重新生成图例:

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.DataFrame({'timepoint': np.random.randint(0, 10, 1000),
      'class': np.random.choice(['cat', 'dog', 'duck', 'hare'], 1000),
      'probability': np.random.rand(1000)
})
ax = sns.lineplot(df, x='timepoint', y='probability', hue='class')

# 获取当前图例的所有句柄和标签
handles, labels = ax.get_legend_handles_labels()

# 指定需要保留的标签
keep_labels = ['cat', 'hare']

# 筛选出要保留的条目
filtered_handles = []
filtered_labels = []
for handle, label in zip(handles, labels):
    if label in keep_labels:
        filtered_handles.append(handle)
        filtered_labels.append(label)

# 重新设置图例
ax.legend(filtered_handles, filtered_labels)
plt.show()

方法2:按索引快速筛选

如果你清楚需要保留的标签在图例中的位置,可以直接通过索引提取:

# 承接上面的绘图代码
handles, labels = ax.get_legend_handles_labels()

# 比如cat是第0个,hare是第3个(根据你的类别顺序)
keep_indices = [0, 3]
filtered_handles = [handles[i] for i in keep_indices]
filtered_labels = [labels[i] for i in keep_indices]

ax.legend(filtered_handles, filtered_labels)
plt.show()

方法3:绘图前控制标签显示

可以先修改数据中的类别标签,把不需要显示的设为空字符串,再过滤掉空标签的图例条目:

# 定义标签映射:需要显示的留原名,不需要的设为空
label_map = {'cat': 'cat', 'dog': '', 'duck': '', 'hare': 'hare'}
df['display_class'] = df['class'].map(label_map)

# 用修改后的列作为hue绘图
ax = sns.lineplot(df, x='timepoint', y='probability', hue='display_class')

# 过滤空标签的图例条目
handles, labels = ax.get_legend_handles_labels()
filtered_handles = [h for h, l in zip(handles, labels) if l != '']
filtered_labels = [l for l in labels if l != '']

ax.legend(filtered_handles, filtered_labels)
plt.show()

这些方法都不依赖旧版Matplotlib的特性,完全适配3.10+版本,而且能完美配合Seaborn的绘图逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 11:12:37