46

I would like to hide the Seaborn pairplot legend. The official docs don't mention a keyword legend. Everything I tried using plt.legend didn't work. Please suggest the best way forward. Thanks!

import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

test = pd.DataFrame({
    'id': ['1','2','1','2','2','6','7','7','6','6'],
    'x': [123,22,356,412,54,634,72,812,129,110],
    'y':[120,12,35,41,45,63,17,91,112,151]})
sns.pairplot(x_vars='x', y_vars="y", 
                 data=test,
                 hue = 'id', 
                 height = 3)
aviss
  • 2,179
  • 7
  • 29
  • 52

4 Answers4

55

Since _legend.remove() method won't work on some other seaborn plots, what about:

plt.legend([],[], frameon=False)
SOJA
  • 631
  • 5
  • 9
44

You need to return the Seabron Pairgrid object when you use pairplot and then you can access the legend of the Pairgrid using ._legend. Then simply call remove():

import seaborn as sns

test = pd.DataFrame({
    'id': ['1','2','1','2','2','6','7','7','6','6'],
    'x': [123,22,356,412,54,634,72,812,129,110],
    'y':[120,12,35,41,45,63,17,91,112,151]})

g = sns.pairplot(x_vars='x', y_vars="y", data=test, hue = 'id', height = 3)
g._legend.remove()

enter image description here

DavidG
  • 24,279
  • 14
  • 89
  • 82
  • 82
    Using `._legend` doesn't work for me and throws an `AttributeError`. Using `.legend_` works, however, as [in this answer](https://stackoverflow.com/a/38136752/9374673). – Mihai Chelaru May 28 '19 at 18:25
  • 1
    @DavidG. Since I see that for most people Mihai Chelaru's answer works, could you please update your answer changing `_legend` to `legend_`? Thank you! – aerijman Jul 07 '20 at 13:34
  • 4
    No. For me, using a `pairplot` my answer works. The linked answer uses a `stripplot` which returns an `axes` object as opposed to the `PairGrid` object returned by `pairplot`, therefore the answers will not be the same. – DavidG Jul 08 '20 at 09:17
  • 3
    `legend_.remove()` works for me for a seaborn lineplot – Jordan Feb 24 '22 at 16:03
9

If you want to remove legends on all subplots, you can use the following code.

fig, axes = plt.subplots(2,5)

# ...

for ax in axes:
    ax.legend([],[], frameon=False)
AndrejH
  • 2,028
  • 1
  • 11
  • 23
1

You can also just stay on the surface roads, so to speak.

ax.get_legend().set_visible(False)
Phil
  • 325
  • 1
  • 3
  • 6