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

如何解决seaborn.kdeplot设置label后仍不显示图例的问题

问题原因

仅给kdeplot设置label参数不会自动在画布上渲染图例,需要手动调用Matplotlib的图例生成方法。

解决方案

方案1:基于现有代码最小改动

在两次kdeplot调用之后,增加一行plt.legend()即可正常显示图例,修改后完整代码如下:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import scipy.stats as stats
from scipy.stats import kruskal
from sklearn.datasets import load_iris

Df1 = pd.read_csv(r"C:\Users\pc admin\Desktop\SUTD Programming\Data Wrangling\Personal Assigment\IBM Data.csv", header=0)

plt.figure(figsize=(20,8))
plt.style.use('seaborn-colorblind')
plt.grid(True, alpha=0.5)
sns.kdeplot(Df1.loc[Df1['Attrition'] == 'No', 'JobSatisfaction'], label = "Previous-Employee")
sns.kdeplot(Df1.loc[Df1['Attrition'] == 'Yes', 'JobSatisfaction'], label ="Current-Employees")
plt.xlabel('JobSatisfaction')
plt.xlim(left=0)
plt.ylabel('Density')
plt.legend() # 新增这一行即可显示图例
# 注意:原标题和x轴内容不匹配,x轴是工作满意度,标题写的是离家距离分布,可按需修正
plt.title('Job Satisfaction Distribution by Attrition Status');
plt.show()

方案2:更符合Seaborn设计规范的写法

不需要手动拆分两个数据集,直接用hue参数按Attrition字段自动分组,会自动生成图例,代码更简洁:

plt.figure(figsize=(20,8))
plt.style.use('seaborn-colorblind')
plt.grid(True, alpha=0.5)
# 用hue自动分组,不用手动筛选子集
sns.kdeplot(data=Df1, x='JobSatisfaction', hue='Attrition')
# 如果需要自定义图例标签,可以加下面这行,顺序对应Attrition的取值顺序(No在前Yes在后)
plt.legend(labels=['Previous-Employee', 'Current-Employees'])
plt.xlabel('JobSatisfaction')
plt.xlim(left=0)
plt.ylabel('Density')
plt.title('Job Satisfaction Distribution by Attrition Status');
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:54:04