7

I am trying to completely remove the legend from lineplots in Seaborn. There are three lineplots in 2x2 subplots, each called like so:

g = sns.lineplot(data=df, dashes=False, ax=axs[0,1])

More specifically, I'd like to get rid of the legend in each of the three line plots, then use the fourth area in the 2x2 plot to display the legend. Any advice is appreciated!

BBrooklyn
  • 350
  • 1
  • 3
  • 15
  • As shown in this [answer](https://stackoverflow.com/a/68849891/7758804). For [`seaborn >= 0.11.2`](https://seaborn.pydata.org/whatsnew.html#v0-11-2-august-2021), to move the legend, use [`seaborn.move_legend`](https://seaborn.pydata.org/generated/seaborn.move_legend.html), which applies to Axes and Figure level plots, and it accepts `kwargs`, like `title`. – Trenton McKinney Dec 23 '22 at 17:49

1 Answers1

10

You can remove each legend for the first three axes, and then use plt.figlegend() which is a legend for the entire figure. You might have to adjust the bbox_to_anchor() arguments based on what is in your legend. (Please ignore the details of my plots which were used solely for illustrative purposes.)

import seaborn as sns

df = sns.load_dataset('flights')

fig, ax = plt.subplots(2,2)

ax1 = sns.lineplot(x=df['year'],y=df['passengers'],
                   color='b',dashes=False,label='ax 1 line',ax=ax[0,0]) 
ax2 = sns.lineplot(x=df['year'],y=df['passengers'],
                   color='r',dashes=False,label='ax 2 line',ax=ax[0,1]) 
ax3 = sns.lineplot(x=df['year'],y=df['passengers'],
                   color='g',dashes=False,label='ax 3 line',ax=ax[1,0])
ax1.get_legend().remove()
ax2.get_legend().remove()
ax3.get_legend().remove()
plt.figlegend(loc='lower right',bbox_to_anchor=(0.85,0.25))

plt.show()

Result:

enter image description here

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
  • 1
    Thanks mm! I also found I can put all the subgraphs into a list and iteratively remove the axes – BBrooklyn May 26 '20 at 19:54
  • `legend=None` (e.g. `sns.lineplot(x=df['year'],y=df['passengers'], color='b',dashes=False,label='ax 1 line',ax=ax[0,0], legend=None)`) is better than `ax1.get_legend().remove()`. `ax1` is redundant - just use `ax[0, 0]`. `ax[1, 1].remove()` to remove an unused subplot. [code and plot](https://i.stack.imgur.com/3K9UU.png) – Trenton McKinney Jan 27 '23 at 19:25