How to map coordinates in AxesImage to coordinates in saved image file?

Posted by Vebjorn Ljosa on Stack Overflow See other posts from Stack Overflow or by Vebjorn Ljosa
Published on 2011-01-12T11:50:24Z Indexed on 2011/01/12 11:53 UTC
Read the original article Hit count: 327

Filed under:
|

I use matplotlib to display a matrix of numbers as an image, attach labels along the axes, and save the plot to a PNG file. For the purpose of creating an HTML image map, I need to know the pixel coordinates in the PNG file for a region in the image being displayed by imshow.

I have found an example of how to do this with a regular plot, but when I try to do the same with imshow, the mapping is not correct. Here is my code, which saves an image and attempts to print the pixel coordinates of the center of each square on the diagonal:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axim = ax.imshow(np.random.random((27,27)), interpolation='nearest')
for x, y in  axim.get_transform().transform(zip(range(28), range(28))):
    print int(x), int(fig.get_figheight() * fig.get_dpi() - y)
plt.savefig('foo.png', dpi=fig.get_dpi())

Here is the resulting foo.png, shown as a screenshot in order to include the rulers:

Screenshot of foo.png with rulers

The output of the script starts and ends as follows:

73 55
92 69
111 83
130 97
149 112
…
509 382
528 396
547 410
566 424
585 439

As you see, the y-coordinates are correct, but the x-coordinates are stretched: they range from 73 to 585 instead of the expected 135 to 506, and they are spaced 19 pixels o.c. instead of the expected 14. What am I doing wrong?

© Stack Overflow or respective owner

Related posts about python

Related posts about matplotlib