moving and removing legend from Seaborn lineplot

Viewed 7572

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!

1 Answers

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

Related