[英]Manually add legend entry to Seaborn Legend
I create overlaying distribution plots by group memberships using我使用组成员身份创建覆盖分布图
gfg = sns.displot(hist_dat, x="Outcome", hue="Group", kind="kde", fill = True,
palette="tab10", height=10.5, aspect=18.5/10.5, legend=True)
gfg._legend.set_title("Group")
plt.setp(gfg._legend.get_title(), fontsize=20)
Now, I add a vertical line to the plot and would like to add an entry for this line to the legend.现在,我在绘图中添加一条垂直线,并希望在图例中添加这条线的条目。 The solution I could make work is
我可以解决的问题是
plt.axvline(x = 0, color = 'b', label = 'ATE')
plt.legend(bbox_to_anchor= (1.1,0.4), frameon=False, title="Effect",
title_fontsize=20)
To get aligned legends, I have to adjust them manually.要获得对齐的图例,我必须手动调整它们。 Is there a more straightforward way to add the ATE legend entry - eg in the existing legend?
是否有更直接的方法来添加 ATE 图例条目 - 例如在现有图例中? Many thanks!
非常感谢!
Result:结果:
Edit: when you use fill, you don't get lines.编辑:当你使用填充时,你不会得到线条。 My bad.
我的错。 Changed the code slightly.
稍微修改了代码。
To do this, you need to specify the handles and labels to the legend argument.为此,您需要为 legend 参数指定句柄和标签。 The way I found to get the
PolyCollection
artists is with ax.get_children()
.我发现获得
PolyCollection
艺术家的方法是使用ax.get_children()
。 Then, you call plt.legend(handles, labels)
.然后,您调用
plt.legend(handles, labels)
。 Here's a toy example:这是一个玩具示例:
sns.displot([0, 1, 2, 2, 3, 3, 4, 4, 5], legend=True, kind='kde', label='test', fill=True)
children = plt.gca().get_children()
l = plt.axvline(3.5, c='r')
plt.legend([children[0], l], ['curve', 'line'] )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.