I'd like to know the coordinates of the bounding rectangle of a text annotation to a Matplotlib plot in figure fraction coordinates. However, when I try to access the "extents" of the patch associated with the annotation, I get Bbox(x0=-0.33, y0=-0.33, x1=1.33, y1=1.33)
regardless of the size of the text label. These coordinates seem to be associated with an IdentityTransform
, but don't transform into any meaningful figure fraction coordinates.
How can I obtain the label's coordinates (ideally, lower left corner and upper right corner) in figure fraction units?
Example:
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return 10 * np.sin(3*x)**4
x = np.linspace(0, 2*np.pi, 100)
y = f(x)
fig, ax = plt.subplots()
ax.plot(x,y)
xpt = 1.75
ypt = f(xpt)
xy = ax.transData.transform([xpt, ypt])
xy = fig.transFigure.inverted().transform(xy)
xytext = xy + [0.1, -0.1]
rdx, rdy = 0, 1
ann = ax.annotate('A point', xy=xy, xycoords='figure fraction',
xytext=xytext, textcoords='figure fraction',
arrowprops=dict(arrowstyle='->', connectionstyle="arc3",
relpos=(rdx, rdy)),
bbox=dict(fc='gray', edgecolor='k', alpha=0.5),
ha='left', va='top'
)
patch = ann.get_bbox_patch()
print(patch.get_extents())
gives:
[[-0.33 -0.33]
[ 1.33 1.33]]
c = patch.get_transform().transform(patch.get_extents())
print(c)
gives:
[[-211.2 -158.4]
[ 851.2 638.4]]
Presumably these are display coordinates, but they don't correspond to the position and size of the label I want the properties of.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…