您可以轻松地在seaborn中做的最酷的事情之一是boxplot + stripplot组合:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

tips = sns.load_dataset("tips")

sns.stripplot(x="day", y="total_bill", hue="smoker",
data=tips, jitter=True,
palette="Set2", split=True,linewidth=1,edgecolor='gray')

sns.boxplot(x="day", y="total_bill", hue="smoker",
data=tips,palette="Set2",fliersize=0)

plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.);

python - Seaborn Boxplot + Stripplot : duplicate legend-LMLPHP

不幸的是,如您在上面看到的,它产生了两个图例,一个用于箱形图,一个用于地带图。显然,它看起来很荒谬和多余。但是我似乎找不到摆脱stripplot图例而只留下boxplot图例的方法。可能可以以某种方式从plt.legend删除项目,但在文档中找不到。

最佳答案

在实际绘制图例本身之前,可以在图例中添加get what handles/labels should exist。然后,仅用所需的特定图例绘制图例。

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

tips = sns.load_dataset("tips")

sns.stripplot(x="day", y="total_bill", hue="smoker",
data=tips, jitter=True,
palette="Set2", split=True,linewidth=1,edgecolor='gray')

# Get the ax object to use later.
ax = sns.boxplot(x="day", y="total_bill", hue="smoker",
data=tips,palette="Set2",fliersize=0)

# Get the handles and labels. For this example it'll be 2 tuples
# of length 4 each.
handles, labels = ax.get_legend_handles_labels()

# When creating the legend, only use the first two elements
# to effectively remove the last two.
l = plt.legend(handles[0:2], labels[0:2], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

python - Seaborn Boxplot + Stripplot : duplicate legend-LMLPHP

关于python - Seaborn Boxplot + Stripplot : duplicate legend,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35538882/

10-11 08:08