Fork me on GitHub

To fix the aspect ratio of a plot, we use the set_aspect method from the axes class. But first, here is an example of what happens when you don't fix the aspect ratio:

In [1]:
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,pi,0.01)
y = np.sin(20*x)

plt.figure(figsize = (5,4))
plt.plot(x,y)
plt.title('plot with undefined aspect ratio')
plt.show()

Now if we change the figure size, the plot gets distored:

In [2]:
plt.figure(figsize=(10,3))
plt.plot(x,y)
plt.title('plot with undefined aspect ratio')
plt.show()

By fixing the aspect ratio we can prevent future distortions. Below, we use the same figure size as the plot above:

In [3]:
plt.figure(figsize=(10,3)) #fig size same as before
ax = plt.gca() #you first need to get the axis handle
ax.set_aspect(1.5) #sets the height to width ratio to 1.5. 
#Use help(ax.set_aspect) for more options.

plt.plot(x,y)
plt.title('plot with Fixed aspect ratio')
plt.show()

Comments