问题描述
您可以轻松地在 seaborn
中做出最酷的事情之一是 boxplot
+ stripplot
组合:
将matplotlib.pyplot导入为plt将seaborn导入为sns将熊猫作为pd导入提示= sns.load_dataset(提示")sns.stripplot(x ="day",y ="total_bill",hue ="smoker",数据=提示,抖动=真实,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.);
不幸的是,如您在上面看到的,它产生了两个图例,一个用于箱形图,一个用于带状图.显然,它看起来很荒谬和多余.但是我似乎找不到摆脱 stripplot
图例而只留下 boxplot
图例的方法.可能可以以某种方式从 plt.legend
中删除项目,但是我无法在文档中找到它.
您可以
One of the coolest things you can easily make in seaborn
is boxplot
+ stripplot
combination:
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.);
Unfortunately, as you can see above, it produced double legend, one for boxplot, one for stripplot. Obviously, it looks ridiculous and redundant. But I cannot seem to find a way to get rid of stripplot
legend and only leave boxplot
legend. Probably, I can somehow delete items from plt.legend
, but I cannot find it in the documentation.
You can get what handles/labels should exist in the legend before you actually draw the legend itself. You then draw the legend only with the specific ones you want.
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.)
这篇关于Seaborn Boxplot + Stripplot:重复图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!