[英]seaborn remove legend in violin plot with swarmplots
我与像群小提琴情节此:
是否可以仅删除 swarmplot 的图例? 似乎传说有 4 个级别,但我只想要前 2 个级别。
我试过ax.legend_.remove()
但删除了所有的图例。
这是我用来制作情节的代码:
import seaborn as sns
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")
ax = sns.swarmplot(x="day", y="total_bill", hue = 'smoker', data=tips, color = 'white', dodge=True)
sns.violinplot(x="day", y="total_bill", hue="smoker",data=tips, palette="muted", ax = ax, )
但是在图例中,它有四个级别,我只是希望删除 swarmplot 的图例级别(黑白点)。
由于我在同样的问题上苦苦挣扎并且找不到答案,因此我决定自己提供答案。 我不确定这是否是最佳解决方案,但我们继续:
正如您已经发现的那样,图例存储在ax.legend_
。 图例只是一个matplotlib.legend.Legend
对象,您可以使用它的句柄( ax.legend_.legendHandles
)和标签(在ax.legend_.texts
作为matplotlib.text.Text
对象列表提供)来更新图例。 使用小提琴图的句柄和相应的标签调用plt.legend(handles, labels)
重新创建没有群图图例条目的图例。 (我交换了两次绘图调用的顺序以使代码更简单。)
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")
ax = sns.violinplot(
x="day", y="total_bill", hue="smoker",
data=tips, palette="muted"
)
handles = ax.legend_.legendHandles
labels = [text.get_text() for text in ax.legend_.texts]
sns.swarmplot(
x="day", y="total_bill", hue="smoker",
data=tips, color="white", dodge=True,
ax=ax # you can remove this, it will be plotted on the current axis anyway
)
plt.legend(handles, labels)
plt.show()
import seaborn as sns
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")
#Your faulted example (what you are getting):
ax = sns.swarmplot(x="day", y="total_bill", hue="smoker", data=tips)
#The right way (what you want to get):
ax = sns.swarmplot(x="day", y="total_bill", data=tips)
sns.violinplot(x="day", y="total_bill", hue="smoker",data=tips, palette="muted", ax = ax)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.