Setting the aspect ratio of a 3D plot in Matplotlib

To set the aspect ratio of a 3D plot in Matplotlib, you can control how the axes are scaled relative to each other. This is particularly useful when you want to ensure proper proportions in your 3D visualizations.

Basic Steps

The process involves the following steps ?

  • Create a new figure using figure() method
  • Get the current axes with projection='3d'
  • Create your 3D data points using NumPy
  • Plot your 3D surface or scatter plot
  • Set the aspect ratio using set_aspect() or set_box_aspect()
  • Optionally adjust viewing angle and save the figure

Example

Here's how to create a 3D surface plot with controlled aspect ratio ?

import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Create mesh data
R, Y = np.meshgrid(np.arange(0, 100, 1), np.arange(0, 60, 1))
z = 0.1 * np.abs(np.sin(R / 40) * np.sin(Y / 6))

# Create surface plot
ax.plot_surface(R, Y, z, cmap=cm.rainbow, linewidth=0)

# Set aspect ratio
ax.set_aspect('auto')

# Set viewing angle
ax.azim = -160
ax.elev = 30

plt.show()

Using set_box_aspect() Method

For more precise control, you can use set_box_aspect() to define exact aspect ratios ?

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(111, projection='3d')

# Create sample data
x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

# Create surface plot
ax.plot_surface(X, Y, Z, cmap='viridis', alpha=0.7)

# Set equal aspect ratio for all axes
ax.set_box_aspect([1, 1, 0.5])  # x:y:z = 2:2:1

ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')

plt.show()

Aspect Ratio Options

Method Description Use Case
set_aspect('auto') Automatic aspect ratio Default scaling
set_aspect('equal') Equal scaling for all axes Geometric accuracy
set_box_aspect([x,y,z]) Custom ratios Precise control

Conclusion

Use set_aspect('auto') for default scaling or set_box_aspect() for precise control over 3D plot proportions. The set_box_aspect() method provides the most flexibility for customizing your 3D visualization's aspect ratio.

Updated on: 2026-03-25T20:09:35+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements