gpt4 book ai didi

python - Seaborn 箱线图 + 条形图 : duplicate legend

转载 作者:IT老高 更新时间:2023-10-28 20:40:15 31 4
gpt4 key购买 nike

您可以在 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.);

boxplot+stripplot

不幸的是,正如您在上面看到的,它产生了双重图例,一个用于箱线图,一个用于条形图。显然,它看起来很荒谬和多余。但我似乎找不到摆脱 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.)

example plot

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

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com