pythonvisualizationseaborn

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.


Solution

  • 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()