Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get bbox in data coordinates in matplotlib

I have the bbox of a matplotlib.patches.Rectangle object (a bar from a bar graph) in display coordinates, like this:

Bbox(array([[ 0.,  0.],[ 1.,  1.]])

But I would like that not in display coordinates but data coordinates. I'm pretty sure this requires a transform. What's the method for doing this?

like image 799
Che M Avatar asked Mar 29 '11 00:03

Che M


1 Answers

I'm not sure how you got the Bbox in display coordinates. Almost everything the user interacts with is in data coordinates (those look like axis or data coordinates to me, not display pixels). The following should fully explain the transforms as they apply to Bboxes:

from matplotlib import pyplot as plt
bars = plt.bar([1,2,3],[3,4,5])
ax = plt.gca()
fig = plt.gcf()
b = bars[0].get_bbox()  # bbox instance

print b
# box in data coords
#Bbox(array([[ 1. ,  0. ],
#       [ 1.8,  3. ]]))

b2 = b.transformed(ax.transData)
print b2
# box in display coords
#Bbox(array([[  80.        ,   48.        ],
#       [ 212.26666667,  278.4       ]]))

print b2.transformed(ax.transData.inverted())
# box back in data coords
#Bbox(array([[ 1. ,  0. ],
#       [ 1.8,  3. ]]))

print b2.transformed(ax.transAxes.inverted())
# box in axes coordinates
#Bbox(array([[ 0.        ,  0.        ],
#       [ 0.26666667,  0.6       ]]))
like image 63
Paul Avatar answered Nov 06 '22 02:11

Paul