I'm making a plot with bars and I'm trying to find their absolute location (in pixels) on the plot for further processing later. It seems to me that this should be able to be figured out from matplotlib's transformation information on the axes instance. Specifically, I'm using ax.transData
to go from data coordinates (where I know the box positions) to display coordinates. Here is some code:
import matplotlib.pyplot as plt
x = range(10)
y = range(1, 11)
fig = plt.figure()
ax = fig.add_subplot(111)
bars = ax.bar(x, y, width=.5, label="foo")
ax.monkey_rectangles = bars
ax.legend()
def get_useful_info(fig):
for ax in fig.get_axes():
for rect in ax.monkey_rectangles:
corners = rect.get_bbox().corners()[::3]
pos = ax.transData.transform(corners)
left = pos[0,0]
width = pos[1,0] - pos[0,0]
bottom = pos[0,1]
height = pos[1,1] - pos[0,1]
yield left, width, bottom, height
fig.savefig('foo.png')
for l, w, b, h in get_useful_info(fig):
print l, w, b, h
This prints the following:
80.0 24.8 48.0 38.4
129.6 24.8 48.0 76.8
179.2 24.8 48.0 115.2
228.8 24.8 48.0 153.6
278.4 24.8 48.0 192.0
328.0 24.8 48.0 230.4
377.6 24.8 48.0 268.8
427.2 24.8 48.0 307.2
476.8 24.8 48.0 345.6
526.4 24.8 48.0 384.0
So, matplotlib thinks my boxes are 24.8 units (pixels I assume) wide. That's fine except when I actually go to measure the box width, I get something more like 32 pixels wide. What is the discrepancy here?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…