python - 删除 seaborn 线图图例标题

标签 python matplotlib seaborn line-plot

我想从我的 seaborn 线图图例中删除标题。我尝试使用 this answer无济于事:

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('')

Seaborn lineplot still with 'event' title

如果我尝试将标题设置为 None,我会得到相同的结果。有趣的是,将标题设置为其他内容似乎会添加到现有标题的前面:

ax.legend().set_title('Something else')

Seaborn lineplot still with prepend title

看起来 seaborn 将标题视为隐藏的传奇条目。我该如何解决这个问题?

最佳答案

重要:这个答案是关于使用 hue 作为图例标题出现的情况。在所有其他情况下,问题本身已经包含摆脱标题的常用方法。

确实,seaborn 滥用了图例标签作为(子组)标题。因此,想法可以是删除此标签,或将其替换为自定义文本。

用自定义文本替换:

legend = ax.legend()
legend.texts[0].set_text("Whatever else")

enter image description here

移除标签:

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles=handles[1:], labels=labels[1:])

enter image description here

删除标签后,您当然还可以设置另一个(真实)标题:

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles=handles[1:], labels=labels[1:], title="Whatever else")

enter image description here

关于python - 删除 seaborn 线图图例标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51579215/

相关文章:

python - 使页面上所有子图的 x 轴长度相同

python - 如何在 python 中使用带有代理身份验证的 requests.post()?

python - pipenv 始终无法安装 psycopg2

python - 无法使用 Matplotlib 在 X 轴上显示时间

python - 如何从绘图窗口或使用命令在 matplotlib 中打印绘图?

matplotlib - 为 seaborn PairGrid 设置不同的轴范围

python - seaborn 修改 y Axis (对数刻度)以显示更多值

python - Discord.py on_member_join 不工作,没有错误信息

python - 使用python 3.7,如何确保正确修改正文内容后正确重新生成已解析的电子邮件而不丢失任何内容?

python - 一张图呈现多个不同大小的饼图