When we deal with geographical data or data which needs equal scaling on both axes the plot representation has to be very accurate. By setting the aspect ratio, we can control the relationship between the width and height of the plot.

Install the matplotlib if you haven’t already installed it using the following command.

pip install matplotlib

Let’s start by importing the necessary libraries and using a sample date to plot the graph.

We can set the aspect ratio using the set_aspect method. In the below example, the property ‘equal’ ensures that the unit length is the same on both axes and the adjustable=’box’ adjusts the plot box to maintain the aspect ratio.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

fig, ax = plt.subplots()
ax.plot(x, y)

# Set the aspect ratio
ax.set_aspect('equal', adjustable='box')

plt.show()

We can also set the custom aspect ratio by passing a numeric value to the set_aspect method.

ax.set_aspect(0.5)

Also, we can set the aspect ratio for 3D plots using the ax.set_box_aspect method available in Matplotlib 3.2.0 and later.

Categorized in:

Tagged in: