I would like to make the axes of a matplotlib plot a square, and do so by stretching or compressing the scaling of the axes rather than by changing the axis limits. How can this be done?
(In other words, I am seeking a Python analog of the MATLAB command axis square
.)
So far, I have tried:
plt.gca().set_aspect('equal')
. This seems to equalize the scaling, rather than the on-screen lengths, of the x and y axes, consistent with the matplotlib documentation. The axes of the resulting plot are not square unless ymax - ymin = xmax - xmin, where xmin, xmax, ymin, and ymax are the axes limits (and this equality does not hold for my plot).
plt.axis('equal')
and plt.axis('scaled')
. These seem to provide the results shown and described in this post. In general, the axes of the resulting plot are not square.
If I understand correctly then I think what you're looking for is ax.set_box_aspect(1)
(also see here), which will give you square axes with the same limits as the original plot.
Example:
import numpy as np
import matplotlib.pyplot as plt
plt.close("all")
x = np.linspace(0, 50, 200)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_box_aspect(1)
fig.tight_layout()