I am plotting a 2D data array with imshow in matplotlib. I have a problem trying to scale the resulting plot. The size of the array is 30x1295 points, but the extent in units are:
extent = [-130,130,0,77]
If I plot the array without the extent, I get the right plot, but if I use extent, I get this plot with the wrong aspect.
It is a pretty beginner question, but there is always a first time: How I can control the aspect and the size of the plot at the same time?
Thanks,
Alex
P.D. The code is, for the right case:
imshow(np.log10(psirhoz+1e-5),origin='lower')
and for the wrong one:
imshow(np.log10(psirhoz+1e-5),origin='lower',
extent =[z_ax.min(),z_ax.max(),rho_ax.min(),rho_ax.max()])
I hope this clarify a bit things.
I'm guessing that you're wanting "square" pixels in the final plot?
For example, if we plot random data similar to yours:
import numpy as np
import matplotlib.pyplot as plt
data = np.random.random((30, 1295))
fig, ax = plt.subplots()
ax.imshow(data, extent=[-130,130,0,77])
plt.show()
We'll get an image with "stretched" pixels:
So, first off, "aspect" in matplotlib refers to the aspect in data coordinates. This means we have to jump through a couple of hoops to get what you want.
import numpy as np
import matplotlib.pyplot as plt
def main():
shape = (30, 1295)
extent = [-130,130,0,77]
data = np.random.random(shape)
fig, ax = plt.subplots()
ax.imshow(data, extent=extent, aspect=calculate_aspect(shape, extent))
plt.show()
def calculate_aspect(shape, extent):
dx = (extent[1] - extent[0]) / float(shape[1])
dy = (extent[3] - extent[2]) / float(shape[0])
return dx / dy
main()
In this case, pyplot.matshow()
might also be useful:
from matplotlib import pyplot as plt
import numpy as np
dat = np.array(range(9)).reshape(3,3)
plt.matshow(dat)
plt.show()
result: