How to zoom imshow in matplotlib without stretching the image?

I wanted to build using imshow in a manner similar to the second example here http://www.scipy.org/Plotting_Tutorial , but to redefine the scale for the axis. I would also like the image to remain still while I do this!

Code from the example:

from scipy import * from pylab import * # Creating the grid of coordinates x,yx,y = ogrid[-1.:1.:.01, -1.:1.:.01] z = 3*y*(3*x**2-y**2)/4 + .5*cos(6*pi * sqrt(x**2 +y**2) + arctan2(x,y)) hold(True) # Creating image imshow(z, origin='lower', extent=[-1,1,-1,1]) xlabel('x') ylabel('y') title('A spiral !') # Adding a line plot slicing the z matrix just for fun. plot(x[:], z[50, :]) show() 

If I change the scale, which will be wider, for example:

 imshow(z, origin='lower', extent=[-4,4,-1,1]) 

Then the resulting image is stretched. But all I wanted to do was change the ticks to match my data. I know that I can use pcolor to save X and Y data, although this has other consequences for it.

I found this answer that allows me to manually redo all the ticks:

How to convert (or scale) axis values โ€‹โ€‹and override tick frequency in matplotlib?

But that seems a little redundant.

Is there a way to change the scale shown by the shortcuts?

+7
source share
1 answer

A help(imshow) will find the aspect argument, which after a little experiment seems to give what you want (a square image of a spiral, but with an x โ€‹โ€‹scale of -4 to 4 and y from -1 to 1) when used as follows:

 imshow(z, origin='lower', extent=[-4,4,-1,1], aspect=4) 

But now your plot is still from -1 to 1, so you will also have to change this ...

 plot(x[:]*4, z[50, :]) 

I think that when you have a few elements that need to be changed, simply using single-line titration with re-labeling will not be redundant:

 xticks(xticks()[0], [str(t*4) for t in xticks()[0]]) 
+11
source

All Articles