您可以通过以下方式获取文本大小get_window_extent文本对象的。这将返回显示坐标(即像素)中文本的边界框,但要获取像素位置,您显然首先需要绘制文本。这样做是通过canvas.draw
缓存渲染器,因此您不需要提供渲染器get_window_extent
(适用于 Windows 和 Linux,对于 macOS,请参阅下面的更新 3)。
import matplotlib.pylab as pylab
fig = pylab.figure()
x, y = 5, 7
text = 'label'
pylab.plot(x, y, 'k.')
t = pylab.text(x, y, text, color='red')
fig.canvas.draw()
print(t.get_window_extent())
pylab.show()
在我的设置中这会导致
Bbox(x0=328.0, y0=234.60000000000036, x1=361.75, y1=248.60000000000036)
Update(见下面的评论):
import matplotlib.pylab as pylab
fig = pylab.figure()
x, y = 5, 7
text = 'label'
pylab.plot(x, y, 'k.')
t = pylab.text(x, y, text, color='red')
fig.canvas.draw()
bbox = t.get_window_extent()
pylab.plot([bbox.x0, bbox.x1, bbox.x1, bbox.x0, bbox.x0],
[bbox.y0, bbox.y0, bbox.y1, bbox.y1, bbox.y0],
'r-',
transform=None)
pylab.show()
更新2:为了让bbox进入数据坐标,您可以使用inverted轴变换,但在添加框之前必须修复 x 和 y 轴限制,否则会触发轴的重新缩放。
import matplotlib.pylab as pylab
fig = pylab.figure()
x, y = 5, 7
text = 'label'
pylab.plot(x, y, 'k.')
xl, yl = pylab.xlim(),pylab.ylim()
t = pylab.text(x, y, text, color='red')
fig.canvas.draw()
bbox = pylab.gca().transData.inverted().transform_bbox(t.get_window_extent())
pylab.plot([bbox.x0, bbox.x1, bbox.x1, bbox.x0, bbox.x0],
[bbox.y0, bbox.y0, bbox.y1, bbox.y1, bbox.y0],
'r-')
pylab.xlim(xl)
pylab.ylim(yl)
pylab.show()
更新3:对于 macOS,您需要显式地将渲染器传递给get_windows_extent
(see here),即上述示例仅在 Windows 和 Linux 上按原样运行。以下内容适用于所有系统:
import matplotlib.pylab as pylab
fig = pylab.figure()
x, y = 5, 7
text = 'label'
pylab.plot(x, y, 'k.')
xl, yl = pylab.xlim(),pylab.ylim()
t = pylab.text(x, y, text, color='red')
renderer = fig.canvas.get_renderer()
bbox = pylab.gca().transData.inverted().transform_bbox(t.get_window_extent(renderer))
pylab.plot([bbox.x0, bbox.x1, bbox.x1, bbox.x0, bbox.x0],
[bbox.y0, bbox.y0, bbox.y1, bbox.y1, bbox.y0],
'r-')
pylab.xlim(xl)
pylab.ylim(yl)
pylab.show()