Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Imshow: extent and aspect

I'm writing a software system that visualizes slices and projections through a 3D dataset. I'm using matplotlib and specifically imshow to visualize the image buffers I get back from my analysis code.

Since I'd like to annotate the images with plot axes, I use the extent keyword that imshow supplies to map the image buffer pixel coordinates to a data space coordinate system.

Unfortuantely, matplotlib doesn't know about units. Say (taking an artificial example) that I want to plot an image with dimensions of 1000 m X 1 km. In that case the extent would be something like [0, 1000, 0, 1]. Even though the image array is square, since the aspect ratio implied by the extent keyword is 1000, the resulting plot axes also have an aspect ratio of 1000.

Is it possible to force the aspect ratio of the plot while still keeping the automatically generated major tick marks and labels I get by using the extent keyword?

like image 456
ngoldbaum Avatar asked Nov 14 '12 18:11

ngoldbaum


People also ask

What is extent in Imshow?

The extent keyword arguments controls the bounding box in data coordinates that the image will fill specified as (left, right, bottom, top) in data coordinates, the origin keyword argument controls how the image fills that bounding box, and the orientation in the final rendered image is also affected by the axes limits ...

How do you scale Imshow?

Use the extent parameter of imshow to map the image buffer pixel coordinates to a data space coordinate system. Next, set the aspect ratio of the image manually by supplying a value such as "aspect=4" or let it auto-scale by using aspect='auto'. This will prevent stretching of the image.


1 Answers

You can do it by setting the aspect of the image manually (or by letting it auto-scale to fill up the extent of the figure).

By default, imshow sets the aspect of the plot to 1, as this is often what people want for image data.

In your case, you can do something like:

import matplotlib.pyplot as plt import numpy as np  grid = np.random.random((10,10))  fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, figsize=(6,10))  ax1.imshow(grid, extent=[0,100,0,1]) ax1.set_title('Default')  ax2.imshow(grid, extent=[0,100,0,1], aspect='auto') ax2.set_title('Auto-scaled Aspect')  ax3.imshow(grid, extent=[0,100,0,1], aspect=100) ax3.set_title('Manually Set Aspect')  plt.tight_layout() plt.show() 

enter image description here

like image 152
Joe Kington Avatar answered Sep 27 '22 17:09

Joe Kington