matplotlib文本框自动定位

matplotlib text boxes automatic position

我想放置一个带有关键字参数的文本框,例如与图例" loc"选项一起使用的参数,即"左上","右上","右下","左下"。
基本目的是使文本框与图例对齐。
我在这里找到了一个建议:在matplotlib中自动放置文本框,但是它仍然使用必须玩的坐标才能获得所需的内容,尤其是如果我想根据文本的长度将其放在绘图区域的右侧时 放在盒子里。 除非我可以将文本框的右上角之一设置为坐标参考。


您可以使用matplotlib的AnchoredText执行此操作。 如下所示:

在matplotlib中自动放置文本框

简单来说:

1
2
3
4
from matplotlib.offsetbox import AnchoredText
anchored_text = AnchoredText("Test", loc=2)
ax.plot(x,y)
ax.add_artist(anchored_text)

每个位置编号对应于轴内的位置,例如loc = 2是"左上方"。 位置的完整列表在此处给出:http://matplotlib.org/api/offsetbox_api.html


如何设置文本相对于图例的位置? 诀窍是,要找到图例的位置,必须先绘制图例,然后再获取bbox。 这是一个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import matplotlib.pyplot as plt
from numpy import random

# Plot some stuff
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(random.rand(10))

# Add a legend
leg = ax.legend('line', loc = 'upper right')

# Draw the figure so you can find the positon of the legend.
plt.draw()  

# Get the Bbox
bb = leg.legendPatch.get_bbox().inverse_transformed(ax.transAxes)

# Add text relative to the location of the legend.
ax.text(bb.x0, bb.y0 - bb.height, 'text', transform=ax.transAxes)
plt.show()

另一方面,如果只需要从右侧定义文本的位置,则可以将水平对齐方式设置为右侧,如下所示:

1
plt.text(x, y, 'text', ha = 'right')