I make a plot with bars, and I try to find their absolute location (in pixels) on the chart for further processing later. It seems to me that this should be understood from the matplotlib transform information on the axis instance. In particular, I use ax.transData
to go from the data coordinates (where I know the positions of the boxes) to display the coordinates. Here is the 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
The following is printed:
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 (the pixels that I guess) are wide. This is great, except when I'm really doing box width measurement, I get something larger than 32 pixels wide. What is the discrepancy here?
source share