[英]Remove seaborn lineplot legend title
I would like to remove the title from my seaborn lineplot legend.我想从我的 seaborn lineplot 图例中删除标题。 I tried using this answer to no avail:
我尝试使用此答案无济于事:
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
fmri = sns.load_dataset("fmri")
fig, ax = plt.subplots()
g = sns.lineplot(x="timepoint", y="signal", hue="event", data=fmri, ax=ax)
ax.legend().set_title('')
I get the same if I try to set the title to None
.如果我尝试将标题设置为
None
我会得到相同的结果。 Interestingly, setting the title to something else seems to prepend to the existing title:有趣的是,将标题设置为其他内容似乎是在现有标题的前面:
ax.legend().set_title('Something else')
It almost looks like seaborn is treating the title as a hidden legend entry.看起来seaborn几乎将标题视为隐藏的图例条目。 How can I resolve this?
我该如何解决这个问题?
Important : This answer is about the case when a hue
is used that appears as a legend title.重要提示:此答案是关于使用显示为图例标题的
hue
的情况。 In all other cases, the question itself already contains the usual way to get rid of a title.在所有其他情况下,问题本身已经包含摆脱标题的常用方法。
Indeed, seaborn is misusing a legend label as a (subgroup-)title.事实上,seaborn 正在滥用图例标签作为(子组)标题。 Hence the idea can be to either remove this label, or replace it with custom text.
因此,想法可以是删除此标签,或将其替换为自定义文本。
Replacing with custom text:替换为自定义文本:
legend = ax.legend()
legend.texts[0].set_text("Whatever else")
Removing the label:去除标签:
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles=handles[1:], labels=labels[1:])
After having removed the label you may of course still set another (real) title:删除标签后,您当然还可以设置另一个(真实的)标题:
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles=handles[1:], labels=labels[1:], title="Whatever else")
import seaborn as sns
g = sns.lineplot(x="myXs", y="myYs", hue="myHue", data=mydf)
g.legend_.set_title(None)
Extending ImportanceOfBeingErnest's answer:扩展ImportanceOfBeingErnest的回答:
I had the same problem, but the 'Removing the label' example removed the title and first item from the actual legend.我遇到了同样的问题,但“删除标签”示例从实际图例中删除了标题和第一项。
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles=handles[1:], labels=labels[1:])
So, this removes just the legend title:因此,这仅删除了图例标题:
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles=handles, labels=labels)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.