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

10

我正在使用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()

然而,每个子图都有由颜色决定的自己的图例。是否可以删除其中一个,并最好将剩余的放在图外?我尝试使用 ax1.legend_.remove(),但没有成功。


1
好的,我已经通过handles解决了这个问题,labels = ax.get_legend_handles_labels() ax.legend(handles[:0], labels[:0]) - JB1
1
你可以使用 factorplot - mwaskom
@mwaskom 这是一个非常出色的函数,但如果我想要显示两个 y 值之间的差异怎么办?Factorplot 的 y 参数不能在子图之间更改,所以您只能创建不同的子图并从 hue 值中提取统一的图例。这值得发布另一个 SO 问题吗? - Charlie G
1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接