I would like to obtain the coordinates of the points of a matplotlib.patches.Rectangle in the "axes" coordinate system, which in https://matplotlib.org/stable/tutorials/advanced/transforms_tutorial.html notes:
"axes" - The coordinate system of the Axes; (0, 0) is bottom left of the axes, and (1, 1) is top right of the axes. -
ax.transAxes...
self.transLimitsis the transformation that takes you from data to axes coordinates; i.e., it maps your view xlim and ylim to the unit space of the axes (andtransAxesthen takes that unit space to display space)
Ok, so consider the following example:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
fig = plt.figure()
ax = fig.add_subplot(111)
plt.autoscale(enable=True, axis='both', tight=None)
x = 0 ; y = 0 ; width = 100; height = 50;
rect = mpatches.Rectangle((x, y), width, height, linewidth=1, edgecolor='black', facecolor='#AAAAAA88')
patch = ax.add_patch(rect)
x = 10 ; y = 10 ; width = 40; height = 20;
rect2 = mpatches.Rectangle((x, y), width, height, linewidth=1, edgecolor='black', facecolor='red')
patch = ax.add_patch(rect2)
print(f"{rect2.get_extents()=}")
print(f"{rect2.get_path().vertices=}")
rdatapoints = rect2.get_patch_transform().transform(rect2.get_path().vertices) # https://stackoverflow.com/a/50315897/6197439
print(f"{rdatapoints=}")
print(f"{ax.transLimits.transform(rdatapoints)=}")
plt.show()
The plot produced is:
Roughly, I'd expect lower left point of rect2 in axes coordinates to be at xy (0.1, 0.2), and the upper right point of rect2 to be at (0.5, 0.6).
However, I don't understand how I can obtain those coordinates; I have tried several things in the code above, and the printout is:
rect2.get_extents()=Bbox([[5040.0, 3748.7999999999997], [24880.0, 11140.8]])
rect2.get_path().vertices=array([[0., 0.],
[1., 0.],
[1., 1.],
[0., 1.],
[0., 0.]])
rdatapoints=array([[10., 10.],
[50., 10.],
[50., 30.],
[10., 30.],
[10., 10.]])
ax.transLimits.transform(rdatapoints)=array([[10., 10.],
[50., 10.],
[50., 30.],
[10., 30.],
[10., 10.]])
So,
rect2.get_extents()produces numbers that are waaaaaaay out of either the data or axes coordinates for that item on the plot;rect2.get_path()apparently keeps it vertices as just straight 0 and 1- I can get the coordinates in "data" coordinate system in
rdatapoints- but trying to transform them withtransLimitsresults in ... exactly the same numbers?!
I really don't understand what is going on here ...
So, how can I get the points of the rect2 Rectangle on the plot in the "axes" coordinate system of the plot?
