如何在seaborn子图中只保留一个传说

JB1*_*JB1 5 python visualization seaborn

我正在使用 seaborn 绘制两个子图,如下所示:

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()
Run Code Online (Sandbox Code Playgroud)

但是,每个子情节都有自己的由颜色决定的图例。是否可以删除其中之一,最好将剩余的放在地块之外?我试过使用,ax1.legend_.remove()但没有用。

小智 8

要使用的代码是:

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()
Run Code Online (Sandbox Code Playgroud)