bbox_to_anchor() 函数的参数

Sou*_*mya 3 python matplotlib legend-properties

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    ax.plot(x, i * x, label='$y = %ix$' % i)

ax.legend(bbox_to_anchor=(1.1, 1.05))

plt.show()
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我遇到了将图例置于任意位置的函数 bbox_to_anchor 。我无法理解该函数的前两个参数,所有文献都说是归一化轴参数。任何机构都可以解释它们是什么以及如何操纵它们吗?

Viv*_*gan 7

尝试通过调整参数来理解 -

ax.legend(bbox_to_anchor=(0,0))
Run Code Online (Sandbox Code Playgroud)

给出了这个 - 在此输入图像描述

它将图例放在左下角。现在假设我希望它位于右上角;我会做

ax.legend(bbox_to_anchor=(1,1))
Run Code Online (Sandbox Code Playgroud)

并会得到 - 在此输入图像描述 所以基本上,这两个参数操纵图例框相对于它们出现的位置的位置 -

如果我将第一个数字设置为 0,图例将位于最左边。如果我将其设置为 1,它将位于最右侧。

如果我将第二个数字设置为 0,则图例框将放置在最底部,将其设置为 1 会将其放置在顶部。

例如,如果我希望图例框出现在右下角,我会将这些参数设置为 (1,0)。

设置 0 到 1 之间的数字将相应地操纵位置。

因此,如果我设置 (0.5,0.5),它将位于中间的某个位置,并且此定位发生在轴上。这就是为什么它在文档中是这样写的。

希望这能解决问题!


Sto*_*ica 5

它不是一个函数,而是一个关键字参数。

摘要:您loc用来指定图例的一个角,并且可以选择bbox_to_anchor指定该角的位置。默认情况下,图例的指定角将放置在轴的同一角上。

例如,loc='upper right'将图例的右上角放置在轴的右上角:

ax.legend(loc='upper right')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

但是,如果您希望图例的右上角位于轴的左中角,您可以使用bbox_to_anchor=(0, 0.5)

ax.legend(loc='upper right', bbox_to_anchor=(0, 0.5))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明