Reputation: 8982
How can I get the coordinates of the box displayed in the following plot?
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'))
I tried to inspect the properties of this object, but I couldn't find something suited to this purpose. There is a property called get_bbox_patch()
which could be on the right track, however, I get results in a different coordinate system (or associated to a different property)
y = x.get_bbox_patch()
y.get_width()
63.265625
Thanks a lot!
Upvotes: 6
Views: 5898
Reputation: 87496
ax.figure.canvas.draw()
bbox = x.get_window_extent()
will return a Bbox
object for your text in display units (the draw
is necessary so that the text is rendered and actually has a display size). You can then use the transforms to convert it to which ever coordinate system you want.
Ex
bbox_data = ax.transData.inverted().transform(bbox)
Upvotes: 6
Reputation: 28868
To your questions there is also a a pre-question:
How can I get the coordinates of the box displayed in the following plot?
, which coordinate system you mean?By default annotate
is done using xytext = None, defaults to xy, and if textcoords = None, defaults to xycoords
.
Since you didn't specify the coordinate system. Your annotation is on the default system. You could specify the data coordinates, which for some purposes is good enough:
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'))
To find the coordinate system, you can do:
In [39]: x.xycoords
Out[39]: 'data'
and to get the coordinates:
In [40]: x.xytext
Out[40]: (0.0, 0.7)
In [41]: x.xy
Out[41]: (0.5, 0)
P.S. not directly related, but the output is from IPython, if you still don't use it, it can boost how you develop in Python and use matplotlib. Give it a try.
Upvotes: 1