Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 57 · 3D, Animation and Advanced

3D Plots

Draw 3D lines, scatter clouds, surfaces, wireframes and contours with projection=3d, set the camera with view_init, and know when 3D hurts readability.

A 3D plot shows a value that depends on two inputs, or points that live in three dimensions. Matplotlib draws these on a normal figure: the 3D Axes projects every point onto the flat screen, using a camera you can rotate. It is not a real 3D engine, but it is good enough for surfaces, point clouds and helix-like curves.

In this lesson you will create a 3D Axes, draw lines, scatter points, surfaces, wireframes and contours, move the camera, and then ask the most important question: does the third dimension actually help the reader? You should already know the object-oriented API, colormaps and how to build grids with NumPy (arrays and meshgrid).

Creating a 3D Axes

A 3D Axes is a normal Axes with projection="3d". In current Matplotlib you do not import anything extra: the projection is registered automatically.

Python
fig = plt.figure(figsize=(6, 5))
ax = fig.add_subplot(projection="3d")

The same keyword works with plt.subplots(subplot_kw={"projection": "3d"}) when you want several 3D panels. The Axes now has three axes (x, y, z), and methods take a third coordinate: ax.plot(x, y, z), ax.scatter(x, y, z), ax.set_zlabel("z"), ax.set_zlim(...).

The 3D toolbox

plot A line through 3D points.
scatter A cloud of separate points.
plot_surface A filled surface z = f(x, y).
plot_wireframe Only the grid lines of a surface.

All of them live on an Axes made with projection="3d".

1 / 2

The mpl_toolkits import in older code

Older tutorials and Stack Overflow answers start every 3D example with from mpl_toolkits.mplot3d import Axes3D, and you will see it in a lot of existing code. That import is where the 3D tools live: the package mpl_toolkits.mplot3d is part of the Matplotlib installation (it is one of the "toolkits" that ship with it), and Axes3D is the class behind every Axes with projection="3d". In old versions the import was what registered the "3d" projection, so leaving it out gave an error. Since Matplotlib 3.2 the registration is automatic, so the import only matters when you want the class itself, for example for isinstance checks, for type hints, or to write projection=Axes3D.name.

Python What the old import gives you

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Both panels are real Axes3D objects; the string "3d" is the registered name of the projection. If an old script's import line shows as "unused" in your editor, that is why: it is harmless, and you can delete it. The other toolkit in this family, mpl_toolkits.axes_grid1, appears in Heatmaps and Images for colorbars that match the height of a plot.

Lines and scatter points in 3D

ax.plot(x, y, z) connects points in order, so it is the tool for trajectories and spirals. ax.scatter(x, y, z, c=...) draws unconnected markers and can colour them by a fourth variable, exactly like the 2D scatter plot.

Python A 3D helix and a point cloud

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that we gave the scatter a colour array through c. That fourth channel is often more useful than a rotated view: it carries a number the reader can compare.

Surfaces and wireframes

A surface plots z = f(x, y) over a grid. You build the grid with np.meshgrid, compute Z with ordinary array maths, and pass three 2D arrays of the same shape to ax.plot_surface(X, Y, Z).

Python
x = np.linspace(-3, 3, 60)
y = np.linspace(-3, 3, 60)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

Useful options for plot_surface:

  • cmap="viridis" colours the surface by height. Pass vmin and vmax to control the range.
  • rstride and cstride (or rcount and ccount) set how coarse the underlying mesh is. Fewer cells render faster.
  • linewidth=0, antialiased=False removes mesh lines for a smooth look.
  • edgecolor="k" with a low alpha shows the structure through the surface.

ax.plot_wireframe(X, Y, Z) draws only the grid lines, which makes it cheap and lets you see through the shape. ax.contour3D(X, Y, Z, levels) draws contour lines at different heights, and ax.contourf(X, Y, Z, zdir="z", offset=...) projects a filled contour onto a wall or the floor.

Python Surface, wireframe and a floor contour

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The floor contour is a classic trick: the 3D shape gives the overall idea and the flat contour gives readable positions.

Setting the camera

Two angles define the viewpoint. elev is the elevation above the xy plane (0 looks from the side, 90 from straight above). azim rotates around the vertical axis. Set them with ax.view_init(elev=..., azim=...). The defaults are elev=30 and azim=-60.

A few more camera tools:

  • ax.set_box_aspect((1, 1, 0.5)) changes the relative size of the box sides, so a tall z range can be flattened.
  • ax.set_proj_type("ortho") turns off perspective, so parallel lines stay parallel. This is better when measurements matter.
  • ax.dist is deprecated; use ax.set_box_aspect(..., zoom=1.2) to zoom.
Python The same surface from four cameras

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last panel (elev=90) is a plan view: you are looking straight down, and the height is only visible through colour. That is really a heatmap, and a flat heatmap or contour is often the better choice from the start.

More 3D plots: contours, triangles, bars, voxels and parametric surfaces

Surfaces from a regular grid are only the start. The same 3D Axes can draw contour lines in space, surfaces from scattered points, 3D bars, cubes and shapes defined by parameters instead of z = f(x, y).

Contours in 3D and triangulated surfaces

ax.contour3D(X, Y, Z, levels) draws the contour lines at their true height, so the lines hug the surface like the rings of a hill. A grid is not always available: when your data is a list of scattered (x, y, z) points (measurements at irregular places), ax.plot_trisurf(x, y, z) builds a surface from triangles between neighbouring points. It needs no meshgrid.

Python contour3D and plot_trisurf

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The triangles come from a Delaunay triangulation of the (x, y) positions. Few points make a coarse, faceted surface; many points approach the smooth one. Never trust the corners of the picture where there are no points: Matplotlib connects the outer points to each other.

Bars and voxels

ax.bar3d(x, y, z, dx, dy, dz) draws a box for every position: x, y, z is the corner at the bottom, and dx, dy, dz are the sizes. It is the 3D bar chart (use it sparingly, see the readability section). ax.voxels(filled) draws unit cubes wherever a 3D Boolean array is True, which is the natural tool for 3D grids, shapes made of cubes and simple volume data.

Python bar3d and voxels

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In bar3d the first three arguments are the near corner of each box, so a bar at column 2 starts at x = 2 and, with dx = 0.7, ends at 2.7. Colours per bar come from a colormap applied to the heights (plt.cm.viridis(heights / heights.max()) returns one RGBA colour per bar). For voxels, the array of booleans decides which cubes exist and an array of colours of the same shape, with a last dimension of 4 (RGBA), colours them.

A Möbius strip: parametric surfaces

Not every surface is z = f(x, y). A sphere, a torus or a twisted band is better described by two parameters (u, v) that run over a rectangle, with x(u, v), y(u, v) and z(u, v) each given by a formula. You make the u, v grid with meshgrid, compute the three coordinate arrays, and pass them to plot_surface. The Möbius strip is a classic: a band that twists half a turn while it goes round.

Python A Möbius strip with plot_surface

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The same pattern draws a torus (a doughnut): X = (R + r*cos(v)) * cos(u), Y = (R + r*cos(v)) * sin(u), Z = r*sin(v) with both parameters from 0 to 2π. Use set_box_aspect with equal numbers so a round shape is not squashed, as in Setting the camera.

When 3D hurts readability

3D charts are impressive and often worse than their 2D equivalents:

  • Occlusion. Front parts hide back parts. A surface can hide a valley.
  • Perspective distortion. Things that are far away look smaller, so you cannot read values from the screen by eye.
  • No gridlines to read from. A point floats in space; you cannot tell its x and y without rotating the view.
  • Static pictures lose the point. In a printed page or a screenshot the reader cannot rotate.

Use 3D when the shape itself is the message (a loss landscape, a terrain, a saddle point). For bar charts, pies and most comparisons, 2D is clearer: 3D bars add decoration but no information. If you must publish a 3D plot, add a colour channel, choose one good angle, add the floor contour, and say what the reader should notice.

If the third variable is a category or a count, try small multiples (several 2D panels) or colour before reaching for projection="3d".

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. How do you create a 3D Axes in current Matplotlib?

    Passing projection="3d" to add_subplot (or subplot_kw in plt.subplots) creates a 3D Axes. The projection is registered automatically, with no extra import needed.
  2. 2. Which arrays does ax.plot_surface(X, Y, Z) expect?

    plot_surface needs the grid coordinates and the heights as 2D arrays of equal shape. np.meshgrid builds X and Y; Z comes from array maths on them.
  3. 3. What does view_init(elev=90, azim=-90) show?

    An elevation of 90 degrees looks straight down at the xy plane, so height is only visible through colour.
  4. 4. Which is a common reason to prefer a 2D chart over 3D?

    Occlusion and perspective make exact reading difficult, and a static picture cannot be rotated. 3D should be reserved for cases where the shape itself is the message.

Summary

  • Create a 3D Axes with fig.add_subplot(projection="3d"); methods take a third coordinate and there are set_zlabel and set_zlim.
  • plot draws 3D lines, scatter draws points (colour can add a fourth variable), plot_surface and plot_wireframe draw z = f(x, y) from meshgrid arrays, and contour3D or contourf(..., zdir, offset) add contours.
  • view_init(elev, azim) sets the camera; set_box_aspect and set_proj_type("ortho") adjust proportions and perspective.
  • Use fewer mesh cells (rstride, cstride) when a surface renders slowly.
  • plot_trisurf builds a surface from scattered points, bar3d draws boxes, voxels draws cubes from a Boolean array, and a parametric surface (Möbius strip, torus) comes from three formulas in two parameters.
  • 3D suffers from occlusion and perspective; prefer 2D heatmaps, contours or small multiples unless the shape is the story.

Next, bend the axes into circles in Polar Plots and Radar Charts.