How to make a square plot with equal axes in Matplotlib

  1. set_aspect()to make a square plot with equal axes
  2. axis() method to generate square plot

We can set the aspect ratio of a plot using the set_aspect() method to make it a square plot and axis() method can also be used to make a square plot with equal axes in Matplotlib.

set_aspect()to make a square plot with equal axes

We can set the aspect ratio using matplotlib.axes.Axes.set_aspect() function. If we use "equal" as an aspect ratio in the function, we get a plot with the same scaling from data points to plot units for X-axis and Y-axis.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-3,3,100)
y = np.sin(x)

fig = plt.figure()
ax = fig.add_subplot(111)

plt.plot(x,y)
plt.xlim(-3,3)
plt.ylim(-3,3)

ax.set_aspect('equal', adjustable='box')

plt.xlabel("x")
plt.ylabel("sinx")

plt.show()

square plot with equal axes using set_aspect to equal.png

plt.xlim(-3,3)
plt.ylim(-3,3)

ax.set_aspect('equal')

It sets both X-axis and Y-axis to have the same range. Then ax.set_aspect('equal') sets both axes to be equal.

The above method only yields a square plot when ranges for both axes are set to be the same. To generate a square plot in the general case, we have to manually set the aspect ratio using the following command:

axes.set_aspect(1./axes.get_data_ratio())

axes.get_data_ratio() gets the ratio of the raw plot data. The value of its reciprocal is passed to set_aspect() to make axes equal without setting the limits of axes manually.

Code:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-3,3,100)
y = np.sin(x)

fig = plt.figure()
ax = fig.add_subplot(111)

plt.plot(x,y)

ax.set_aspect(1.0/ax.get_data_ratio(), adjustable='box')

plt.xlabel("x")
plt.ylabel("sinx")
plt.show()

square plot with equal axes using set_aspect general

axis() method to generate square plot

If we pass "square" as an argument to matplotlib.pyplot.axis(), it creates a square plot where the ranges for both axes occupy are equal to the length in plot.

import numpy as np
import matplotlib.pyplot as plt

x=np.linspace(-3,3,100)
y=np.sin(x)
plt.plot(x,y)
plt.axis('square')
plt.xlabel("x")
plt.ylabel("sinx")
plt.show()

square plot with equal axes using axis methodl

Warning

The range of axes in this solution are selected automatically. It is equal to ax.set_aspect('equal', adjustable='datalim'). The explicit axis limits set by the user are not respected.

Related Article - Matplotlib Axes

  • How to add a y-axis label to secondary y-axis in Matplotlib
  • How to plot logarithmic axes in Matplotlib
  • How to set limits for axes in Matplotlib
  • How to reverse axes in Matplotlib
  • How to turn off the axes for subplots in Matplotlib
  • comments powered by Disqus