6

如何获得下图中显示的框的坐标?

在此处输入图像描述

fig, ax = subplots()
x = ax.annotate('text', xy=(0.5, 0), xytext=(0.0,0.7), 
                ha='center', va='bottom',
                bbox=dict(boxstyle='round', fc='gray', alpha=0.5),
                arrowprops=dict(arrowstyle='->', color='blue'))

我试图检查这个对象的属性,但我找不到适合这个目的的东西。有一个名为的属性get_bbox_patch()可能在正确的轨道上,但是,我在不同的坐标系中得到结果(或与不同的属性相关联)

y = x.get_bbox_patch()
y.get_width()
63.265625

非常感谢!

4

2 回答 2

6
ax.figure.canvas.draw()
bbox = x.get_window_extent()

Bbox将以显示单位为您的文本返回一个对象(这draw是渲染文本并实际具有显示大小所必需的)。然后,您可以使用变换将其转换为您想要的任何坐标系。前任

bbox_data = ax.transData.inverted().transform(bbox) 
于 2013-07-23T15:50:05.967 回答
1

对于您的问题,还有一个前置问题:

  • 当你写的时候How can I get the coordinates of the box displayed in the following plot?,你指的是哪个坐标系?

默认情况下annotate使用xytext = None, defaults to xy, and if textcoords = None, defaults to xycoords.

由于您没有指定坐标系。您的注释在默认系统上。您可以指定数据坐标,这对于某些目的来说已经足够了:

x = ax.annotate('text', xy=(0.5, 0), xytext=(0.0,0.7), 
                ha='center', va='bottom', textcoords='data', xycoords="data",
                bbox=dict(boxstyle='round', fc='gray', alpha=0.5),
                arrowprops=dict(arrowstyle='->', color='blue'))

要查找坐标系,您可以执行以下操作:

In [39]: x.xycoords
Out[39]: 'data'

并获取坐标:

In [40]: x.xytext
Out[40]: (0.0, 0.7)

In [41]: x.xy
Out[41]: (0.5, 0)

PS 不直接相关,但输出来自IPython,如果您仍然不使用它,它可以促进您在 Python 中开发和使用 matplotlib 的方式。试试看。

于 2013-07-23T05:24:25.360 回答