Add legend to CDF plot

Question:

I am having little difficulty adding legend to a CDF plot with seaborn.

MWE:

import numpy as np
import matplotlib.plyplot as plt
import seaborn as sns

X = np.random.randn(20,1,10,4)
k = X[:,0,:,0].reshape(-1)
l  = X[:,0,:,1].reshape(-1)
m  = X[:,0,:,2].reshape(-1)
n  = X[:,0,:,3].reshape(-1)

plt.figure()
plt.title('Some Distribution ')
plt.ylabel('CDF')
plt.xlabel('x-labelled)')
sns.kdeplot(k,cumulative=True, legend=True)
sns.kdeplot(l,cumulative=True, legend=True)
sns.kdeplot(m,cumulative=True, legend=True)
sns.kdeplot(n,cumulative=True, legend=True)
plt.show()

enter image description here

Also:

plt.figure()
plt.title('Some Distribution ')
plt.ylabel('CDF')
plt.xlabel('x-labelled)')
sns.kdeplot(k,cumulative=True)
sns.kdeplot(l,cumulative=True)
sns.kdeplot(m,cumulative=True)
sns.kdeplot(n,cumulative=True)
plt.legend(labels=['legend1', 'legend2', 'legend3', 'legend4'])
plt.show()

enter image description here

Asked By: arilwan

||

Answers:

legend = True is the default in seaborn.kdeplot, so you have no need to specify it. However, what you do need to specify is the labels.

sns.kdeplot(k,cumulative=True, label = 'a')
sns.kdeplot(l,cumulative=True, label = 'b')
sns.kdeplot(m,cumulative=True, label = 'c')
sns.kdeplot(n,cumulative=True, label = 'd')

Outputs:

enter image description here

Even in your second example, with plt.legend(labels=['legend1', 'legend2', 'legend3', 'legend4']), you need to first specify labels in seaborn.kdeplot(). If you pass different labels in plt.legend() the labels passed to searbon.kdeplot() will be replaced, but if no labels are passed to seaborn, I get the same output as you (i.e. no legend at all).

Example:

sns.kdeplot(k,cumulative=True, label = 'a')
sns.kdeplot(l,cumulative=True, label = 'b')
sns.kdeplot(m,cumulative=True, label = 'c')
sns.kdeplot(n,cumulative=True, label = 'd')
plt.legend(labels = ['1','2','3','4'])

Outputs:

enter image description here

Answered By: dm2