Search code examples
pythonmatplotlibgraphaxes

How to require equal axes in matplotlib


I was used to using a version of python where the code below generated exactly proportional axes.

    plt.ylabel("y(Km)")
    plt.gca().set_aspect('equal')
    ax = plt.axes()
    ax.set_facecolor("black")
    circle = Circle((0, 0), 2, color='dimgrey')
    plt.gca().add_patch(circle)
    plt.axis([-1 / u1 , 1 / u1 , -1 / u1 , 1 / u1 ])

When I switched computers and started using python 3.7, the same code started to generate a desconfigured picture. Why did this happen and how can I resolve it? The before and after photos are below.

Before

After


Solution

  • Your code is creating two overlapping axes (as you point out in the red circles in the second image). You can see that also by running the following lines at the end of your code:

    print(plt.gcf().get_axes()) # (get current figure)
    

    Which gives:

    [<AxesSubplot:ylabel='y(Km)'>, <AxesSubplot:>]
    

    This happens because while you have already an axes, you add another by the line ax = plt.axes(). From documentation:

    Add an axes to the current figure and make it the current axes.
    

    Maybe you meant ax = plt.gca() ?

    Anyway, tidying up the code:

    import matplotlib.pyplot as plt
    from matplotlib.patches import Circle
    
    u1 = 0.05
    
    fig, ax = plt.subplots() # figure fig with one axes object ax
    ax.set_facecolor("black")
    ax.set_aspect("equal")
    circle = Circle((0, 0), 2, color='dimgrey')
    ax.add_patch(circle)
    ax.set_xlim([-1 / u1, 1 / u1 ])
    ax.set_ylim([-1 / u1, 1 / u1 ])
    ax.set_ylabel("y (km)")
    
    print(fig.get_axes()) # not needed for anything, just for comparison with original code
    
    plt.show()
    

    Which should give: enter image description here