Setting the aspect ratio of a 3D plot in Matplotlib

MatplotlibPythonData Visualization

To set the aspect ratio of a 3D plot in matplotlib, we can take the following steps−

  • Using figure() method, create a new figure or activate an existing figure.
  • Get the current axes, creating one if necessary, with projection='3d'.
  • Create data points, R, Y and z, using numpy.
  • Create a surface plot using R, Y and z.
  • Set the aspect ratio using set_aspect('auto').
  • Save the figure using savefig() method.


from matplotlib import 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.gca(projection='3d')
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))
ax.plot_surface(R, Y, z, cmap=cm.rainbow, linewidth=0)
ax.azim = -160
ax.elev = 30


Updated on 15-May-2021 12:34:51