繁体   English   中英

matplotlib、seaborn 中的“plt.legend”:“loc”参数如何工作?

[英]`plt.legend` in matplotlib, seaborn: How does the `loc` parameter work?

  • 我是 Python 的初学者,正在学习在线课程。 以下是课程中给定解决方案的抽象版本。
  • 在一个练习中,生成了seaborn plot 并添加了legend
  • 问题:根据使用的参数,我不明白图例在右侧的情况。 loc = 'center left'如何将legend放在 plot 的右侧?
  • matplotlib手册说:

字符串 'upper center'、'lower center'、'center left'、'center right' 将图例放置在轴/图形相应边缘的中心。

  • 我确信有一个合乎逻辑的答案,但我看不到它:)。

代码清单

import pandas as pd
import seaborn as sb

# https://www.geeksforgeeks.org/different-ways-to-create-pandas-dataframe/
# initialize data of lists.
data = {'Name':['Tim', 'Tom', 'Cindy', 'Mandy'],
        'Age':[20, 21, 19, 18],
        'Gender':['Male', 'Male', 'Female', 'Female']}
 
# Create DataFrame
df = pd.DataFrame(data)

sb.barplot(data = df, x = 'Name', y = 'Age',  hue = 'Gender')
plt.legend(loc = 'center left', bbox_to_anchor = (1, 0.5)) # legend to right of figure

截图

在此处输入图像描述

在此处输入图像描述

https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html

当您还为bbox_to_anchor传递坐标参数时,对loc的解释会发生不直观的变化。 当两者都存在时,图例框loc锚定在bbox_to_anchor坐标上。

因此,您所做的是要求它对齐图例,使框在轴的 (1, .5) 坐标上左对齐并垂直居中,这将其置于 plot 之外的右侧。

把它放在你期望的地方,你可以做loc="center left", bbox_to_anchor=(0, .5) 或者只是不设置bbox_to_anchor ,这仅在您想将 position 微调到您可以在loc中拼出的 9 个点之外时才真正相关。 例如,如果您想要轴右下角的图例,但从角落填充一点,您可以执行loc="lower right", bbox_to_anchor=(.85, .15)

我相信这是由于图形和轴之间的差异。

Matplotlib 有两个对象:图形和轴。 一个图是 matplotlib 正在绘制的整体 plot,轴是用于绘制某些东西的各个轴。 例如,您可能有一个带有四个轴的图形,用于四个单独的子图。

您可以在没有轴的情况下工作,例如

plt.plot(x,y)

或使用轴,例如

fig, ax = plt.subplots(1,1)
ax.plot(x,y)

我相信(并且希望有经验的人更深入地研究这种区别)通常使用轴更好,因为它可以在您创建更复杂的图形时为您提供更多控制。

那么,这与 Seaborn 有什么关系呢? 好吧,我很确定 Seaborn 总是与轴一起工作。 这意味着plt.legend在任何活动图形上绘制图例,而不是在 Seaborn 绘制的特定轴上。 因此,正常的放置选项不起作用。

您可以做的是创建一个变量来获取由 Seaborn 创建的轴,以便您可以在该轴上绘制图例:

ax = sb.barplot(data = df, x = 'Name', y = 'Age',  hue = 'Gender')
ax.legend(loc = 'center left', bbox_to_anchor = (1, 0.5))

或者,您可以在绘图之前定义轴。

fig, ax = plt.subplots(1,1)
sb.barplot(data = df, x = 'Name', y = 'Age',  hue = 'Gender', ax=ax)
ax.legend(loc = 'center left', bbox_to_anchor = (1, 0.5))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM