matplotlib中注释框的坐标

2024-04-26 03:04:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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

enter image description here

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()的属性可能在正确的轨道上,但是,我在不同的坐标系(或与不同的属性关联)中得到结果

^{pr2}$

非常感谢!在


Tags: text绘图属性figaxdictcenterxy
2条回答
ax.figure.canvas.draw()
bbox = x.get_window_extent()

将返回一个以显示单位表示的文本的^{}对象(必须使用draw以便呈现文本并具有实际的显示大小)。然后可以使用变换将其转换为所需的任何坐标系。 前

^{pr2}$

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

  • 当你写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'))

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

^{pr2}$

为了得到坐标:

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

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

p.S.不是直接相关的,但是输出来自IPython,如果您仍然不使用它,它可以提高您在Python中开发和使用matplotlib的方式。试试看。在

相关问题 更多 >