Python Seaborn箱线图+;条形图:重复图例
在Python Seaborn箱线图+;条形图:重复图例,python,matplotlib,legend,seaborn,Python,Matplotlib,Legend,Seaborn,在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", sp
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
legend的方法,只留下boxplot
legend。也许,我可以从plt.legend
中删除项目,但我在文档中找不到它。在绘制图例之前,您可以在图例中找到它。然后,仅使用所需的特定图例绘制图例
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.)
我想补充一点,如果使用子图,图例处理可能会有点问题。顺便说一句,上面的代码给出了一个非常好的数字(@Sergey Antopolskiy和@Ffisegydd),它不会在子图中重新定位图例,而子图一直显示得非常顽固。参见上面适用于子批次的代码:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
tips = sns.load_dataset("tips")
fig, axes = sns.plt.subplots(2,2)
sns.stripplot(x="day", y="total_bill", hue="smoker",
data=tips, jitter=True, palette="Set2",
split=True,linewidth=1,edgecolor='gray', ax = axes[0,0])
ax = sns.boxplot(x="day", y="total_bill", hue="smoker",
data=tips,palette="Set2",fliersize=0, ax = axes[0,0])
handles, labels = ax.get_legend_handles_labels()
l = plt.legend(handles[0:2], labels[0:2], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
原来的传说仍然存在。要删除它,可以添加以下行:
axes[0,0].legend(handles[:0], labels[:0])
编辑:在seaborn(>0.9.0)的最新版本中,这用于在注释中指出的角落中留下一个白色小框。要解决此问题,请使用:
在
seaborn
0.9.0中,这会在第一个图中留下一个白色的小框作为空白图例。
axes[0,0].get_legend().remove()