0

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

Imports and sample data

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)

Example 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

Example 2

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

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
arilwan
  • 3,374
  • 5
  • 26
  • 62

1 Answers1

1

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

dm2
  • 4,053
  • 3
  • 17
  • 28