pythonmatplotlibaxis

When using matplotlib, how do I set the on-screen lengths of the x and y axes to be equal without changing the limits of either axis?


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:


Solution

  • 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()