Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep only one legend in seaborn subplots

I am plotting two subplots using seaborn like so:

fig, (ax1, ax2) = plt.subplots(ncols=2, sharey=True)

sns.swarmplot(flowers[0], flowers[1], hue=colours, ax=ax1)
ax1.set(xlabel='Sepal Length', ylabel='Sepal Width')
plt.legend(loc="upper left", bbox_to_anchor=(1, 1))

sns.swarmplot(flowers[2], flowers[3], hue=colours, ax=ax2)
ax2.set(xlabel='Petal Length', ylabel='Petal Width')

sns.plt.show()

However, each subplot has its own legend dictated by colours. Is it possible to remove one of these, and preferably place the remaining outside of the plot? I have tried using ax1.legend_.remove() but that didn't work.

like image 627
JB1 Avatar asked Feb 19 '17 20:02

JB1


Video Answer


1 Answers

the code to be used is:

fig, (ax1, ax2) = plt.subplots(ncols=2, sharey=True)

sns.swarmplot(flowers[0], flowers[1], hue=colours, ax=ax1)
ax1.set(xlabel='Sepal Length', ylabel='Sepal Width')
plt.legend(loc="upper left", bbox_to_anchor=(1, 1))

sns.swarmplot(flowers[2], flowers[3], hue=colours, ax=ax2)
ax2.set(xlabel='Petal Length', ylabel='Petal Width')
ax2.get_legend().remove()


sns.plt.show()
like image 88
Valerio Ficcadenti Avatar answered Sep 28 '22 05:09

Valerio Ficcadenti