It’s not perfectly clear what your desired outcome is.
-
You may use automatic aspect on the image
ax.imshow(z, aspect="auto")
-
Or you may set the aspect of the line plot depending on its axis limits such that it gets the same size as the image (in case the image has equal x and y sizes)
asp = np.diff(ax2.get_xlim())[0] / np.diff(ax2.get_ylim())[0] ax2.set_aspect(asp)
Complete code:import numpy as np import matplotlib.pyplot as plt x = np.linspace(0,10,20) y = np.sin(x) z = np.random.rand(100,100) fig, (ax, ax2) = plt.subplots(ncols=2) ax.imshow(z) ax2.plot(x,y, marker=".") asp = np.diff(ax2.get_xlim())[0] / np.diff(ax2.get_ylim())[0] ax2.set_aspect(asp) plt.show()If the image does not have equal limits (is not square), one still needs to divide by the aspect of the image:
asp = np.diff(ax2.get_xlim())[0] / np.diff(ax2.get_ylim())[0] asp /= np.abs(np.diff(ax1.get_xlim())[0] / np.diff(ax1.get_ylim())[0]) ax2.set_aspect(asp) -
More sophisticated solutions:
-
This answer for using the subplot parameters to achieve a certain aspect.
-
If you want to use
mpl_toolkitsand make your hands dirty, this answer would be a good read.
-