matplotlib 中的图例在对 bbox_to_anchor 参数进行最小更改的情况下跳跃

问题描述 投票:0回答:1

我在 matplotlib 中遇到这个问题,这让我发疯。我想将图例放置在图中的某个位置,例如,在本例中,位于左上角(与图的角匹配)。我不想使用

loc
参数,因为它没有给我想要的确切位置。为了实现我想要的,我使用
bbox_to_anchor
。问题是,只要对
x,y
参数进行最小的更改,图例就会到处乱跳。为什么会发生这种情况?这是怎么回事?我该如何解决它?

例如

bbox_to_anchor=(0.12,.9)

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig, ax = plt.subplots(1,1)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.arctan(x), label='Inverse tan')
ax.legend(bbox_to_anchor=(0.12,.9))

plt.show()

并与

bbox_to_anchor=(0.13,.9)

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig, ax = plt.subplots(1,1)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.arctan(x), label='Inverse tan')
ax.legend(bbox_to_anchor=(0.13,.9))

plt.show()

最后还有

bbox_to_anchor=(0.13,.8)

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig, ax = plt.subplots(1,1)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.arctan(x), label='Inverse tan')
ax.legend(bbox_to_anchor=(0.13,.8))

plt.show()

谢谢!

python matplotlib legend
1个回答
0
投票

添加@JohanC的评论以及我对matplotlib图例的source的解释:首先设置

bbox_to_anchor
,然后是图例的
set_loc
。因此,如果您不指定
loc
,则将使用默认值并将您的
bbox_to_anchor
值应用于图例(无法追踪使用哪个默认值)。将此视为暂时将您的图例绘制到人物上。然后稍后
loc
将被更新,因为默认情况下使用
best
,它会等到绘制图形来计算最佳位置。由于您的图例已临时绘制在您的人物上,“最佳”位置的计算可能会返回一个新的
loc
值而不是默认值。然后,使用新的
bbox_to_anchor
将您的
loc
值再次应用于图例。

简而言之,如果您想要可预测的行为,只需设置

loc

© www.soinside.com 2019 - 2024. All rights reserved.