6

I like the Seaborn example of multiple bivariate KDE plots, but I was hoping to use a standard matplotlib legend instead of the custom labels in that example.

Here's an example where I tried to use a legend:

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

cmaps = ['Reds', 'Blues', 'Greens', 'Greys']

np.random.seed(0)
for i, cmap in enumerate(cmaps):
    offset = 3 * i
    x = np.random.normal(offset, size=100)
    y = np.random.normal(offset, size=100)
    label = 'Offset {}'.format(offset)
    sns.kdeplot(x, y, cmap=cmaps[i]+'_d', label=label)
plt.title('Normal distributions with offsets')
plt.legend(loc='upper left')
plt.show()

Plot with no legend

The label parameter to kdeplot() seems to work for univariate KDE plots, but not for bivariate ones. How can I add a legend?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Don Kirkby
  • 53,582
  • 27
  • 205
  • 286

1 Answers1

11

Based on this tutorial, I learned that you can pass the labels in to the legend() function.

import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np

cmaps = ['Reds', 'Blues', 'Greens', 'Greys']

np.random.seed(0)
label_patches = []
for i, cmap in enumerate(cmaps):
    offset = 3 * i
    x = np.random.normal(offset, size=100)
    y = np.random.normal(offset, size=100)
    label = 'Offset {}'.format(offset)
    sns.kdeplot(x, y, cmap=cmaps[i]+'_d')
    label_patch = mpatches.Patch(
        color=sns.color_palette(cmaps[i])[2],
        label=label)
    label_patches.append(label_patch)
plt.title('Normal distributions with offsets')
plt.legend(handles=label_patches, loc='upper left')
plt.show()

Plot with legend

Don Kirkby
  • 53,582
  • 27
  • 205
  • 286