Skip to content

Matplotlib - 3D Wireframe plot

A 3D wireframe plot visualizes a three-dimensional surface defined by Z = f(X, Y) by drawing lines connecting the grid points. It essentially shows the ‘skeleton’ or underlying grid structure of the surface, making it useful for understanding the surface’s form without the potential occlusion caused by filled surface plots.

Like other 3D plots in Matplotlib, wireframe plots require a 3D Axes object (projection='3d') and typically take 2D arrays for X, Y, and Z coordinates (often created using numpy.meshgrid).

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

ax.plot_wireframe(X, Y, Z, **kwargs)
  • X, Y, Z: 2D arrays representing the x, y, and z coordinates of the surface grid points.
  • color: A single color specification for all wireframe lines.
  • linewidth: Width of the wireframe lines.
  • linestyle: Style of the wireframe lines (e.g., '-', '--', ':').
  • rstride, cstride: Integers. Downsampling stride for rows and columns. Plotting every nth grid line can simplify the plot and speed up rendering for dense grids (e.g., rstride=2, cstride=2 plots every second line).

Example: Plotting a 3D wireframe for a sinusoidal function.

import matplotlib.pyplot as plt
import numpy as np
# 1. Define the function to plot
def f(x, y):
return np.sin(np.sqrt(x**2 + y**2))
# 2. Create coordinate vectors and grids
x_vec = np.linspace(-6, 6, 30)
y_vec = np.linspace(-6, 6, 30)
X, Y = np.meshgrid(x_vec, y_vec)
# 3. Calculate Z values
Z = f(X, Y)
# 4. Create the figure and 3D axes
fig = plt.figure(figsize=(8, 6))
ax = plt.axes(projection='3d')
# 5. Create the wireframe plot
# Use rstride/cstride to potentially simplify the mesh if needed
wireframe_plot = ax.plot_wireframe(X, Y, Z,
color='black', # Color of the wires
linewidth=0.5, # Thin lines
rstride=1, # Plot every 1st row line
cstride=1 # Plot every 1st column line
)
# 6. Set labels and title
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
ax.set_title('3D Wireframe Plot')
# Adjust view angle (optional)
ax.view_init(elev=40, azim=-45)
plt.show()

This code generates the X, Y, and Z coordinate grids for the function f(x, y) and then uses ax.plot_wireframe() to draw the surface structure using black lines. The rstride and cstride parameters control the density of the wireframe mesh; larger values create a sparser grid. Wireframe plots provide a clear view of the surface’s underlying grid and shape.