Search code examples
pythonmatplotlibimshow

axis positioning with imshow - python


I have been trying to add two axes on the same figure, with very specific locations. The problem is that when I add the plot, they seem to have different sizes to what I specified.

Here is an example

fig = plt.figure()
ax = fig.add_axes([0.0, 0.3, 0.7, 0.7])

M = np.random.random([10, 20])
ax.imshow(M)

plt.show()

This is the result

enter image description here

However, when I use ax.plot() instead it seems to place the axis at the correct location.

enter image description here

My feeling is that it has to do with the aspect ratio in imshow() but nothing has worked for me so far. Any suggestions? Thanks in advance


Solution

  • You are correct; the imshow aspect, which is set to "equal" by default prevents the axes to scale automatically to the position specified. Usually this is desired though, because you want square pixels in an imshow plot.

    In order to set the aspect to automatic, use

    ax.imshow(M, aspect="auto")