我正在尝试绘制一个图形,其中我有一个位于网格 (1, 5) 处的文本对象,我想绘制一个从对象底部中心向下的箭头。问题是,我不知道那个中心坐标在哪里。 y坐标显然是5左右,但是x坐标取决于物体的长度。
我想做的只是类似 Arrow(1 + obj.x_size/2, 5, etc.) 但我无法找到实际获取大小的方法对象本身。我应该使用什么?
即
t = ax.text(0.5, 5, r'$x_n = (2.1, 4.4) \in R^2$', fontsize=18)
ax.arrow(???, 5, 0, -2, fc='k', ec='k', head_width=0.5, head_length=1)
请您参考如下方法:
您可以使用get_window_extent() 方法获取文本的边界框。这将在显示坐标中,这不是您想要的箭头。您需要使用转换将显示坐标转换为数据坐标。为了使其正常工作,轴限制需要是您完成图形后的任何大小。这意味着在获得边界框之前,您需要手动设置 x 和 y 轴限制或绘制您计划绘制的所有内容。然后,将边界框转换为数据坐标,获取角的坐标,并使用它们来制作箭头。
import matplotlib.pyplot as plt
from matplotlib.transforms import TransformedBbox
fig, ax = plt.subplots()
t = ax.text(0.5, 5, r'$x_n = (2.1, 4.4) \in R^2$', fontsize=18)
#draw the plot so it's possible to get the bounding box
plt.draw()
#either plot everything or set the axes to their final size
ax.set_xlim((0, 10))
ax.set_ylim(0, 10)
#get the bbox of the text
bbox = t.get_window_extent()
#get bbox in data coordinates
tbbox = TransformedBbox(bbox, ax.transData.inverted())
coords = tbbox.get_points()
#get center of bbox
x = (coords[1][0] + coords[0][0]) / 2
#get bottom of bbox
y = coords[0][1]
ax.arrow(x, y, 0, -2, fc='k', ec='k', head_width=0.5, head_length=1)
plt.show()
