在 seaborn tsplot 中将图例移到图外

新手上路,请多包涵

我想使用 seaborn.tsplot 创建一个时间序列图 --- 就像 这个例子中的 tsplot 文档,但是图例向右移动,在图中之外。

例子

基于 seaborn 的 timeseries.py 中的第 339-340 行,它看起来像 seaborn.tsplot 目前不允许直接控制图例放置:

     if legend:
        ax.legend(loc=0, title=legend_name)

有 matplotlib 解决方法吗?我正在使用 seaborn 0.6-dev。

原文由 bnelsj 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
1 个回答

20220916 更新

seaborn 的 v0.11.2 版本开始,有图例位置的内置控件,请参阅 seaborn.move_legend 。将图例放在外面:

 ax = sns.histplot(penguins, x="bill_length_mm", hue="species")
sns.move_legend(ax, "upper left", bbox_to_anchor=(1, 1))

在此处输入图像描述

旧答案

确实, seaborn 到目前为止还不能很好地处理图例。根据 Matplotlib 图例指南,您可以使用 plt.legend() 直接通过 matplotlib 控制图例属性。

请注意,在 Seaborn 0.10.0 tsplot 中被删除,您可以复制(如果需要,可以使用不同的估计值)带有 lineplot 而不是 tsplot 的图 ---

片段

import matplotlib.pyplot as plt
import seaborn as sns

sns.set(style="darkgrid")

# Load the long-form example gammas dataset
gammas = sns.load_dataset("gammas")

# Plot the response with standard error
sns.lineplot(data=gammas, x="timepoint", y="BOLD signal", hue="ROI")

# Put the legend out of the figure
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

输出

修改图例位置

原文由 Sergey Antopolskiy 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏