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

如何在Seaborn折线图中仅保留hue图例,移除style相关图例?

当然可以在Seaborn框架内搞定这个需求。核心思路是先正常绘图,然后手动过滤或重建图例,只保留protocol对应的条目。

给你两种可行的方法:

方法一:筛选原图例中的protocol条目

先绘制图形,然后从自动生成的图例里提取出仅和protocol相关的部分,替换掉原来的图例:

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

df = pd.DataFrame({
    'name':['A','A','B','B','C','C','D','D'],
    'date':[1,2,1,2,1,2,1,2],
    'strenght':[1,10,2,5,6,5,10,20],
    'protocol':['a','a','b','b','a','a','b','b']})

# 绘制图形并获取轴对象
ax = sns.lineplot(data=df, x='date', y='strenght', hue='protocol', style='name')

# 获取原图例的手柄和标签
handles, labels = ax.get_legend_handles_labels()

# 筛选出protocol对应的标签(这里是'a'和'b')
target_labels = ['a', 'b']
selected_handles = []
selected_labels = []
for h, l in zip(handles, labels):
    if l in target_labels:
        selected_handles.append(h)
        selected_labels.append(l)

# 替换原有图例
ax.legend(selected_handles, selected_labels, title='protocol')

plt.show()

方法二:重建仅包含protocol的图例

先移除自动生成的图例,然后基于protocol的配色手动创建新图例:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.patches import Patch

df = pd.DataFrame({
    'name':['A','A','B','B','C','C','D','D'],
    'date':[1,2,1,2,1,2,1,2],
    'strenght':[1,10,2,5,6,5,10,20],
    'protocol':['a','a','b','b','a','a','b','b']})

# 绘制图形并获取轴对象
ax = sns.lineplot(data=df, x='date', y='strenght', hue='protocol', style='name')

# 移除原有图例
ax.legend_.remove()

# 生成protocol对应的配色
protocols = df['protocol'].unique()
palette = sns.color_palette(n_colors=len(protocols))
color_map = dict(zip(protocols, palette))

# 创建新图例的手柄
handles = [Patch(color=color_map[prot], label=prot) for prot in protocols]

# 添加新图例
ax.legend(handles=handles, title='protocol')

plt.show()

两种方法都能实现你的需求:只显示protocol的图例,且只有对应两种颜色,同时保留name对应的线条样式差异。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 17:02:30