3D Plots in Matplotlib: Surface, Scatter, Wireframe, and Bar

Make 3D plots in Matplotlib with projection="3d", including surface plots, 3D scatter, wireframes, contour projections, 3D lines and bars, and set the viewing angle.

To make a 3D plot in Matplotlib, create an axes with projection="3d", then call ax.plot_surface(), ax.scatter(), ax.plot_wireframe(), or ax.plot() on it. Surfaces need 2D grids of x and y values, which you build with np.meshgrid.

Quick Example

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-4, 4, 120)
y = np.linspace(-4, 4, 120)
X, Y = np.meshgrid(x, y)
Z = np.sinc(np.sqrt(X**2 + Y**2) / 1.6)

fig, ax = plt.subplots(figsize=(8, 6), subplot_kw={"projection": "3d"})
surface = ax.plot_surface(X, Y, Z, cmap="viridis", linewidth=0, antialiased=True)
fig.colorbar(surface, ax=ax, shrink=0.6, pad=0.1, label="z")
ax.set_title("3D surface plot")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
plt.show()

Matplotlib 3D surface plot of a ripple shape with a tall central peak, colored with viridis and shown with a colorbar

The surface has a central peak of height 1 surrounded by a ring that dips to about -0.22. There's no extra import to remember: since Matplotlib 3.2, projection="3d" works without importing Axes3D. The code targets Matplotlib 3.10 and 3.11.

Which 3D Plot Method Should I Use?

Method Input Good for
plot_surface 2D arrays X, Y, Z Functions and gridded data
plot_wireframe 2D arrays X, Y, Z Seeing the shape and what's behind it
plot_trisurf 1D arrays x, y, z Surfaces from scattered, non-gridded points
scatter 1D arrays x, y, z Point clouds and clusters
plot 1D arrays x, y, z Paths and trajectories
contour, contourf 2D arrays plus zdir, offset Flat contours projected onto a wall or floor
bar3d positions and sizes Values on a two-way category grid

If you create the figure first, add the 3D axes with ax = fig.add_subplot(projection="3d"). The old fig.gca(projection="3d") form no longer works and raises a TypeError.

3D Scatter Plot

ax.scatter takes a third coordinate. Plot one group per call so each gets its own color and legend entry.

rng = np.random.default_rng(17)
centers = {"Compact": (1.3, 120, 7.0), "Sedan": (1.6, 170, 8.0), "SUV": (2.1, 210, 10.0)}
colors = {"Compact": "#0d9488", "Sedan": "#d97706", "SUV": "#7c3aed"}

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(projection="3d")
for name, (weight, power, fuel) in centers.items():
    w = rng.normal(weight, 0.14, 70)
    p = rng.normal(power, 18, 70)
    f = rng.normal(fuel, 0.6, 70)
    ax.scatter(w, p, f, color=colors[name], s=28, label=name)
ax.set_xlabel("Weight (t)")
ax.set_ylabel("Power (hp)")
ax.set_zlabel("Fuel use (L/100 km)")
ax.set_title("3D scatter plot of three car classes")
ax.legend(loc="upper left")
plt.show()

Matplotlib 3D scatter plot with three separate clusters of compact cars, sedans, and SUVs across weight, power, and fuel use

The three classes separate cleanly, with SUVs heaviest, most powerful, and thirstiest. Matplotlib fades points that are farther from the camera (depthshade=True). Pass depthshade=False if the color needs to match the legend exactly.

Wireframe Plot and Contour Projection

plot_wireframe draws only the grid lines. rstride and cstride set how many rows and columns to skip between lines. Calling contourf with zdir="z" flattens the contours onto a plane at offset, which gives the reader an undistorted top view under the surface.

Z2 = np.exp(-((X - 1) ** 2 + (Y - 1) ** 2) / 2) - 0.8 * np.exp(-((X + 1.5) ** 2 + (Y + 1) ** 2) / 3)

fig = plt.figure(figsize=(10, 4.8))
ax1 = fig.add_subplot(1, 2, 1, projection="3d")
ax1.plot_wireframe(X, Y, Z2, rstride=6, cstride=6, color="#1d4ed8", linewidth=0.8)
ax1.set_title("plot_wireframe")

ax2 = fig.add_subplot(1, 2, 2, projection="3d")
ax2.plot_surface(X, Y, Z2, cmap="coolwarm", alpha=0.85)
ax2.contourf(X, Y, Z2, zdir="z", offset=-1.8, cmap="coolwarm", levels=12)
ax2.set_zlim(-1.8, 1)
ax2.set_title("Surface with a contour projection")
plt.show()

A blue 3D wireframe of a peak and a valley beside the same surface colored red and blue with filled contours projected onto the floor

Change the Viewing Angle with view_init

ax.view_init(elev, azim) points the camera. elev is the height above the x-y plane in degrees and azim is the rotation around the vertical axis. The defaults are elev=30 and azim=-60.

views = [(30, -60, "default"), (90, -90, "top down"), (0, -90, "front"), (20, 30, "rotated")]
fig, axes = plt.subplots(1, 4, figsize=(12, 3.6), subplot_kw={"projection": "3d"})
for ax, (elev, azim, name) in zip(axes, views):
    ax.plot_surface(X, Y, Z2, cmap="coolwarm", linewidth=0)
    ax.view_init(elev=elev, azim=azim)
    ax.set_title(f"{name}\nelev={elev}, azim={azim}", fontsize=11)
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.set_zticklabels([])
plt.show()

The same 3D surface from four camera angles: the default view, straight down, from the front, and rotated

To rotate with the mouse, run the script in a desktop window, or in Jupyter install ipympl and run %matplotlib widget. The default inline backend only shows a static image.

3D Line Plot

Use ax.plot with three arrays. set_box_aspect changes the proportions of the plot box.

t = np.linspace(0, 8 * np.pi, 600)
fig = plt.figure(figsize=(7, 5.5))
ax = fig.add_subplot(projection="3d")
ax.plot(np.cos(t) * (1 + t / 12), np.sin(t) * (1 + t / 12), t, color="#be123c", linewidth=2.2)
ax.set_title("3D line plot: an expanding spiral")
ax.set_box_aspect((1, 1, 1.2))
plt.show()

Red 3D line plot of a spiral that widens as it rises

3D Bar Chart with bar3d

ax.bar3d(x, y, z, dx, dy, dz) draws each bar from a corner at (x, y, z) with the given width, depth, and height. Flatten the grid into 1D arrays first.

cities = ["Oslo", "Lisbon", "Cairo"]
quarters = ["Q1", "Q2", "Q3", "Q4"]
sales = np.array([[18, 26, 31, 22], [27, 34, 45, 33], [39, 42, 36, 48]])
xpos, ypos = np.meshgrid(np.arange(4), np.arange(3))
xpos, ypos, dz = xpos.ravel(), ypos.ravel(), sales.ravel()

fig = plt.figure(figsize=(8, 5.5))
ax = fig.add_subplot(projection="3d")
bar_colors = np.array(["#0ea5e9", "#f59e0b", "#10b981"])[ypos]
ax.bar3d(xpos, ypos, 0, 0.6, 0.5, dz, color=bar_colors, shade=True)
ax.set_xticks(np.arange(4) + 0.3, labels=quarters)
ax.set_yticks(np.arange(3) + 0.25, labels=cities)
ax.set_zlabel("Sales ($k)")
ax.set_title("3D bar chart with bar3d")
ax.view_init(elev=25, azim=-55)
plt.show()

3D bar chart of quarterly sales for Oslo, Lisbon, and Cairo, with the back row partly hidden by the rows in front

This chart shows the usual problem with 3D bars: front bars hide the ones behind, and heights are hard to read. A grouped bar chart or a heatmap shows the same 12 numbers more accurately.

Practical Tips

  • plot_surface samples at most 50 rows and 50 columns by default. Raise rcount and ccount for a finer surface; rendering gets slower.
  • If z labels are clipped when saving, use fig.savefig(..., bbox_inches="tight", pad_inches=0.3).
  • Matplotlib sorts whole objects by depth rather than individual pixels, so intersecting surfaces can overlap incorrectly. For heavy 3D work, use Plotly, PyVista, or Mayavi.
  • When the exact values matter, a filled contour or colorbar-labeled heatmap is easier to read than a surface.

Similar Topics