Edwin Eng
Edwin Eng

Reputation: 35

How to display Legend with seaborn.kdeplot

I have been trying add the Legend to my code below. It should have worked when I add the "Label". But it just won't show, not sure what I did wrong.

Packages Used

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.title('Distance From Home Distribution in Percent by Attrition Status');

enter image description here enter image description here

Upvotes: 1

Views: 2308

Answers (2)

Kartik Joshi
Kartik Joshi

Reputation: 1

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

import matplotlib.patches as mpatches


Df1 = pd.r`enter code here`ead_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.title('Distance From Home Distribution in Percent 
by Attrition Status')

handles = [mpatches.Patch(facecolor=plt.cm.Reds(100), 
label="Active Employee"),
       mpatches.Patch(facecolor=plt.cm.Blues(100), 
label="Ex employee")]
plt.legend(handles=handles)
# chose whatever colour you want hope thats help you 
#out :)
#legends was deprecated in python 3 if you have object 
of #sns.kdeplot

Upvotes: 0

Guimoute
Guimoute

Reputation: 4649

You simply need to call the .legend() method of your Axes object. The plotting functions of seaborn return the reference to the Axes directly which is handy. See the documentation of sns.kdeplot

ax = sns.kdeplot(...)
ax.legend(loc="upper right")

Upvotes: 4

Related Questions