36

I am coming to Python and numpy and matplotlib from a Matlab background. One function in matlab that I use all the time is imagesc. Is there an exact equivalent to this somewhere in matplotlib? I know about imshow and pcolor, but the first doesn't allow you to easily set the units of the axes like imagesc, and the second makes you set the x- and y-coordinates of the boundaries of the pixels, rather than the centers of the pixels, which I do not find intuitive.

Basically, if I have an image that I want to display with x- and y-axis labels that are not pixel numbers but are numerical, like distance in mm, what is the easiest way to do it in matplotlib?

Matt
  • 2,846
  • 2
  • 17
  • 12

1 Answers1

31

You want the extent kwarg

ax.imshow(data, extent=[0, 1, 0, 1])

See Imshow: extent and aspect for a more detailed example.

Community
  • 1
  • 1
tacaswell
  • 84,579
  • 22
  • 210
  • 199
  • That's helpful, thank you, I had overlooked that kwarg in the imshow documentation. It seems that the extent arg sets coordinates of the edges of the image, right? So one task this this doesn't solve is assigning coordinates to the centers of pixels, if that's what I want to do. – Matt May 20 '13 at 18:23
  • 1
    From the `extent` documentation: "Data limits for the axes. The default assigns zero-based row, column indices to the x, y centers of the pixels." It does what you want by default. That said, I think it may have changed between mpl versions at some point. – tacaswell May 20 '13 at 18:27
  • Well, I mean assigning coordinates of my choice to the centers of pixels, not just the pixel number. – Matt May 20 '13 at 20:02
  • use `extent=[-.5 + x_start, x_end + .5, y_start - .5, y_end + .5]`. – tacaswell May 20 '13 at 20:12
  • Note that @tcaswell 's comment is not the general case, and will only work if your pixels are 1 unit apart. You want to use 0.5dx, where dx is the spacing of your pixels. So, for example, if your pixels are separated by 5mm, you would do: `extent=[-2.5 + x_start, x_end + 2.5, y_start - 2.5, y_end + 2.5]` – Caleb Mar 04 '15 at 18:28
  • @Caleb Working in the god-given units of pixels ;) – tacaswell Mar 04 '15 at 19:17