TExcelTAD
Home › Matplotlib › 3D Plots

3D Plots

Matplotlib includes a 3D toolkit, mplot3d, which adds a third axis to the Axes. It can draw 3D lines, scatter plots, surfaces and wireframes. The figures are projected onto a flat image, so 3D plots are best for getting an impression of a shape; for reading exact values, a contour plot or heatmap is usually clearer.

Creating 3D Axes

Ask for the "3d" projection. In modern Matplotlib no extra import is needed:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(0, 6 * np.pi, 400)
x = np.cos(t)
y = np.sin(t)
z = t / (2 * np.pi)            # one unit of height per turn

fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
ax.plot(x, y, z, lw=2)
ax.set(xlabel="x", ylabel="y", zlabel="turns", title="A helix")
plt.show()

print("Axes type:", ax.name)
print(f"Height reached: {z[-1]:.1f} turns")
Axes type: 3d
Height reached: 3.0 turns

3D Axes have a third set of methods for the z axis: set_zlabel, set_zlim, set_zticks …

3D scatter

ax.scatter(x, y, z) places points in space. Colouring them by a value helps the eye separate depth:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(17)
centres = np.array([[0, 0, 0], [4, 4, 0], [2, 0, 4]])
points = np.vstack([c + rng.normal(0, 0.8, (60, 3)) for c in centres])
label = np.repeat([0, 1, 2], 60)

fig, ax = plt.subplots(figsize=(6, 5), subplot_kw={"projection": "3d"})
ax.scatter(points[:, 0], points[:, 1], points[:, 2], c=label, cmap="viridis", s=15)
ax.set(xlabel="x", ylabel="y", zlabel="z", title="Three clusters")
plt.show()

for k in range(3):
    print(f"cluster {k} centre:", np.round(points[label == k].mean(axis=0), 2).tolist())
cluster 0 centre: [0.0, -0.16, 0.08]
cluster 1 centre: [3.81, 3.9, -0.12]
cluster 2 centre: [2.02, 0.09, 4.01]

Surfaces

plot_surface(X, Y, Z) takes the same meshgrid input as a contour plot. A colormap shades the surface by height:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-4, 4, 80)
y = np.linspace(-4, 4, 80)
X, Y = np.meshgrid(x, y)
R = np.sqrt(X ** 2 + Y ** 2)
Z = np.sin(R) / (R + 1e-9)        # a "ripple" (avoid dividing by 0)

fig, ax = plt.subplots(figsize=(7, 5), subplot_kw={"projection": "3d"})
surf = ax.plot_surface(X, Y, Z, cmap="coolwarm", linewidth=0, antialiased=True)
fig.colorbar(surf, ax=ax, shrink=0.6, pad=0.1)
ax.set_title("sin(r) / r")
plt.show()

print("Grid:", Z.shape, "| peak height:", round(float(Z.max()), 3))
Grid: (80, 80) | peak height: 0.999

Viewing angle and wireframes

ax.view_init(elev, azim) turns the camera: elev is the height angle above the x-y plane, azim the rotation around the z axis (both in degrees). A wireframe draws only the grid lines, which shows the shape without hiding what's behind:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

X, Y = np.meshgrid(np.linspace(-2, 2, 30), np.linspace(-2, 2, 30))
Z = X ** 2 - Y ** 2              # a saddle

fig, axes = plt.subplots(1, 2, figsize=(9, 4), subplot_kw={"projection": "3d"})
axes[0].plot_wireframe(X, Y, Z, rstride=2, cstride=2, color="C0", linewidth=0.7)
axes[0].set_title("default view")

axes[1].plot_wireframe(X, Y, Z, rstride=2, cstride=2, color="C2", linewidth=0.7)
axes[1].view_init(elev=10, azim=20)
axes[1].set_title("elev=10, azim=20")
plt.show()

print("view of right panel:", axes[1].elev, axes[1].azim)
print("default view:", axes[0].elev, axes[0].azim)
view of right panel: 10 20
default view: 30 -60

rstride and cstride draw every n-th row and column of the grid, keeping a wireframe from becoming too dense.

Surface plus contour projection

A common trick combines a surface with its contour lines projected onto the floor, so the reader gets both the 3D impression and readable levels:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

X, Y = np.meshgrid(np.linspace(-3, 3, 60), np.linspace(-3, 3, 60))
Z = np.exp(-(X ** 2 + Y ** 2) / 2) - 0.6 * np.exp(-((X - 1.5) ** 2 + (Y - 1) ** 2))

fig, ax = plt.subplots(figsize=(7, 5), subplot_kw={"projection": "3d"})
ax.plot_surface(X, Y, Z, cmap="viridis", alpha=0.85)
ax.contour(X, Y, Z, levels=10, zdir="z", offset=-1, cmap="viridis")
ax.set_zlim(-1, 1)
ax.set(xlabel="x", ylabel="y", zlabel="z")
plt.show()

print("z limits:", [float(v) for v in ax.get_zlim()])
z limits: [-1.0, 1.0]

zdir="z", offset=-1 projects the contours onto the plane z = −1, which is why the z limits start there.

Method (3D Axes) Draws
plot(x, y, z) 3D line
scatter(x, y, z) 3D points
plot_surface(X, Y, Z) shaded surface
plot_wireframe(X, Y, Z) grid-line surface
contour(X, Y, Z, zdir=..., offset=...) contour lines in 3D or projected
bar3d(x, y, z, dx, dy, dz) 3D bars
view_init(elev, azim) camera angle

Tip: In a desktop window or Jupyter with an interactive backend you can rotate 3D plots with the mouse. The images in this playground are static, so use view_init to choose a good angle.

Test yourself

How do you create a 3D Axes?

  1. plt.subplots(dim=3)
  2. plt.subplots(subplot_kw={"projection": "3d"})
  3. plt.axes3d()
  4. ax.set_3d(True)

What does ax.view_init(elev=90, azim=0) show?

  1. A side view
  2. A view from directly above
  3. A view from below
  4. Nothing, the angles are invalid

Which input does plot_surface expect?

  1. Three 1-D arrays of points
  2. 2-D grids X, Y, Z (e.g. from meshgrid)
  3. A single 2-D array
  4. A list of polygons