Skip to content

Matplotlib - 3D Surface plot

A 3D surface plot is used to visualize a three-dimensional surface representing a function Z = f(X, Y). It’s similar to a wireframe plot, but instead of just lines, the faces of the grid defined by the X, Y, and Z coordinates are filled with colored polygons. The color often represents the height (Z value) of the surface, aiding in the perception of the surface’s topology.

Like other 3D plots in Matplotlib, surface plots require a 3D Axes object created using the projection='3d' keyword. The data X, Y, and Z must typically be 2D arrays representing coordinates on a grid (often created using numpy.meshgrid).

The ax.plot_surface() method is used to create these plots.

ax.plot_surface(X, Y, Z, **kwargs)
  • X, Y, Z: 2D arrays representing the x, y, and z coordinates of the surface grid points.
  • cmap: String or Colormap instance. Specifies the colormap used to color the surface based on Z values (e.g., ‘viridis’, ‘plasma’, ‘coolwarm’).
  • color: A single color specification if you want the entire surface to be one color (overrides cmap).
  • edgecolor: Color for the edges of the surface patches (setting to 'none' can sometimes produce a smoother look).
  • linewidth: Width of the edge lines.
  • rstride, cstride: Integers. Downsampling stride for rows and columns. Plotting every nth grid line can speed up rendering for large surfaces.
  • alpha: Float (0-1). Transparency of the surface.

Example: Plotting a 3D surface for Z = cos(sqrt(X^2 + Y^2)).

import matplotlib.pyplot as plt
import numpy as np
# 1. Create coordinate vectors and grids
x_vec = np.linspace(-5, 5, 50)
y_vec = np.linspace(-5, 5, 50)
X, Y = np.meshgrid(x_vec, y_vec)
# 2. Calculate Z values based on the function
R = np.sqrt(X**2 + Y**2)
Z = np.cos(R)
# 3. Create the figure and 3D axes
fig = plt.figure(figsize=(9, 7))
ax = plt.axes(projection='3d')
# 4. Create the surface plot
# Use a colormap (cmap) to color based on Z height
surface_plot = ax.plot_surface(X, Y, Z,
cmap='viridis', # Colormap for coloring
edgecolor='black', # Color of mesh lines
linewidth=0.2, # Width of mesh lines
alpha=0.9 # Surface transparency
)
# Optionally, remove edges for a smoother look:
# surface_plot = ax.plot_surface(X, Y, Z, cmap='viridis', edgecolor='none')
# 5. Add a color bar to map colors to Z values
fig.colorbar(surface_plot, shrink=0.5, aspect=10, label='Z value (cos(R))')
# 6. Set labels and title
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
ax.set_title('3D Surface Plot')
# Set Z limits if necessary (e.g., to focus on a range)
# ax.set_zlim(-1.0, 1.0)
# Adjust view angle (optional)
ax.view_init(elev=30, azim=45) # elev=elevation, azim=azimuth
plt.show()

This code generates the X, Y, and Z coordinate grids for the function and then uses ax.plot_surface() to render the 3D surface. The cmap='viridis' argument colors the surface based on the Z value, and a colorbar is added to provide a key. Adjusting parameters like edgecolor, linewidth, alpha, and the viewpoint (ax.view_init) allows for significant customization of the plot’s appearance.