0

我用这样的蜂群制作了一个小提琴 情节

是否可以仅删除 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的图例级别(黑白点)。

4

2 回答 2

2

由于我正在努力解决同样的问题并且找不到答案,我决定自己提供一个答案。我不确定这是否是最佳解决方案,但我们开始吧:

正如您已经知道的那样,图例存储在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()
于 2021-04-15T19:45:03.247 回答
0
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)
于 2019-02-24T18:38:36.263 回答