Python MatPlotLib—对象的大小

Python MatPlotLib—对象的大小,python,matplotlib,Python,Matplotlib,我试图画一个图形,其中有一个文本对象位于网格上的(1,5),我想画一个从对象底部中心向下的箭头。问题是,我不知道中心坐标在哪里。y坐标显然是5左右,但x坐标取决于对象的长度 我想做的是类似于箭头(1+obj.x_size/2、5等)但我很难找到一种方法来实际获取对象本身的大小。我应该用什么 i、 e 您可以使用get\u window\u extent()方法获取文本的边界框。这将显示在显示坐标中,而不是箭头所需的坐标。您需要使用转换将显示坐标转换为数据坐标。为了使其正常工作,轴限制必须是绘制图

我试图画一个图形,其中有一个文本对象位于网格上的(1,5),我想画一个从对象底部中心向下的箭头。问题是,我不知道中心坐标在哪里。y坐标显然是5左右,但x坐标取决于对象的长度

我想做的是类似于
箭头(1+obj.x_size/2、5等)
但我很难找到一种方法来实际获取对象本身的大小。我应该用什么

i、 e


您可以使用
get\u window\u 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()

您可以添加示例代码吗?
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()