50

I am new to plotting in python and trying following code to plot distribution in seaborn but unable to see the legend, i.e., test_label1 and test_label1 on the plot.

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

plt.figure("Test Plots")
lst1 = list(np.random.rand(10))
lst2 = list(np.random.rand(10))
sns.distplot(lst1, label='test_label1', color="0.25")
sns.distplot(lst2, label='test_label2', color="0.25")

plt.show()
Rahul
  • 755
  • 4
  • 8
  • 16
  • 4
    `plt.legend()`? – DavidG Jul 07 '17 at 10:02
  • Thanks @DavidG. This works but the only problem with this is that I have to do it separately at the end. So something like `plt.legend(['test_label1', 'test_label2'])` will require to remember the ordering. – Rahul Jul 07 '17 at 10:07
  • 2
    You don't have to do that as you have already specified `label=` in your plot. Calling `plt.legend()` before `plt.show()` will work (it does for me) – DavidG Jul 07 '17 at 10:11

3 Answers3

79

As you have already labelled your plots using label= inside your sns.distplot then all you have to do is show your legend. This is done by adding plt.legend() just before plt.show()

More information on matplotlib legends can be found in the documentation

DavidG
  • 24,279
  • 14
  • 89
  • 82
  • 5
    Is that really the "Seaborn way", to use matplotlib directly for a legend? – matanster Sep 10 '18 at 11:34
  • @matanster I don't really see any problem because seaborn is essentially just a wrapper for matplotlib anyway. There are ways to get a legend to appear using just arguments of `sns.distplot`, however IMO it's not as simple – DavidG Sep 27 '18 at 10:51
11

By using fig.legend we can show legends in the distribution plot. Here, an argument array of labels is passed to the function. Labels in the legend will also be displayed as an order of array values.

import seaborn as sns
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(10,6))
lst1 = list(np.random.rand(10))
lst2 = list(np.random.rand(10))
sns.distplot(lst1)
sns.distplot(lst1)
fig.legend(labels=['test_label1','test_label2'])
plt.show()
Vlad
  • 8,225
  • 5
  • 33
  • 45
  • 7
    Code-only answers are considered as low quality posts, [edit] your answer and add some explanation – barbsan May 06 '19 at 10:36
4

I found some issue using "fig.legend()" to adding labels into legend in seaborn histogram. It reverse colors order in legend without changing colors of histogram bars...

fig.legend(labels=['label1','label2',...])

Histogram before using fig.legend()

Histogram after using fig.legend()

Modules versions:

  • seborn '0.11.0'
  • matplotlib '3.1.3'

Simple solution is to reverse the order of label_list by appling label_list.reverse() but I don't consider it as good solution. I don't have idea what is happening and how to block reversing the order of colors in legend.

DamianJot
  • 41
  • 4