seaborn 使用 swarmplots 删除小提琴情节中的传说

seaborn remove legend in violin plot with swarmplots

我用蜂群做了一个小提琴图 this:

是否可以只删除群图的图例?传说好像有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 的图例级别(黑白点)。

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)

由于我一直在为同样的问题苦苦挣扎,找不到答案,所以我决定自己提供答案。我不确定这是否是最佳解决方案,但我们开始吧:

如您所知,图例存储在 ax.legend_ 中。图例只是一个 matplotlib.legend.Legend object and you can use its handles (ax.legend_.legendHandles) and labels (provided in ax.legend_.texts as a list of matplotlib.text.Text objects) to update the legend. Calling 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()