Some data depend on two variables and give a surface. Matplotlib can draw such three-dimensional graphs with an extra axis.

Creating a 3D Axis

A 3D graph needs an axis created with projection="3d", for example ax = plt.axes(projection="3d") or fig.add_subplot(projection="3d"). The plotting methods then take three arguments, x, y and z. The viewing angle can be changed with ax.view_init(elevation, azimuth), and the mouse can rotate the graph in an interactive window.

Types of 3D Plots

A line in space is drawn with ax.plot3D(x, y, z), and separate points with ax.scatter3D(x, y, z). A surface plot, drawn with ax.plot_surface(X, Y, Z), shows z as a function of x and y. To build it, np.meshgrid(x, y) makes two grids that cover every pair of x and y values, and Z is calculated from them, for example Z = np.sin(np.sqrt(X 2 + Y 2)). Colours can be added with the cmap argument, which maps height to colour.

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-5, 5, 50)
X, Y = np.meshgrid(x, x)
Z = np.sin(np.sqrt(X ** 2 + Y ** 2))
ax = plt.axes(projection="3d")
ax.plot_surface(X, Y, Z, cmap="viridis")
plt.show()

Definition: Surface plot. A three-dimensional graph in which the height z is shown as a surface over a grid of x and y values.

A three-dimensional graph should be used only when the third dimension carries real information, because a flat graph is often easier to read. The colour map can show the height as well, and plt.colorbar() adds a scale that explains the colours. Surface plots are common in science and engineering, for example to show temperature over a plate, the error of a model for two parameters, or the shape of a mathematical function. The wireframe form, drawn with plot_wireframe, shows only the grid lines and is lighter than a full surface. A graph can be saved with plt.savefig before show is called, so that it can be placed in a report.

Table 4.5: Two-dimensional and three-dimensional plots

Item 2D 3D
Axis plt.plot plt.axes(projection="3d")
Line plot(x, y) plot3D(x, y, z)
Points scatter(x, y) scatter3D(x, y, z)
Surface Not available plot_surface(X, Y, Z)

Example 4.5: Building the grid for a surface

Problem: Show what np.meshgrid returns for x = [1, 2, 3] and y = [10, 20].

Solution:

  1. Call np.meshgrid(x, y).
  2. Print the two grids that it returns.

Result: Each grid has 2 rows and 3 columns, so every pair of x and y values is covered.

import numpy as np
X, Y = np.meshgrid([1, 2, 3], [10, 20])
print(X)
print(Y)
print((X + Y).shape)

Output

[[1 2 3]
 [1 2 3]]
[[10 10 10]
 [20 20 20]]
(2, 3)

Common mistakes

  • Forgetting projection="3d" and getting an error when calling a 3D method.
  • Passing one-dimensional arrays to plot_surface instead of grids from meshgrid.
  • Using a very large grid, which makes the plot slow.

Key takeaways

  • A 3D axis is created with projection="3d".
  • plot3D draws a line and scatter3D draws points in space.
  • plot_surface needs two-dimensional grids from np.meshgrid.
  • ax.view_init changes the viewing angle.

Practice questions

  1. How is a 3D axis created in Matplotlib?
  2. What does np.meshgrid do?
  3. Which method draws a 3D surface?

Answers to the practice questions

  1. With projection="3d".
  2. Makes grids of x and y values that cover every pair of values.
  3. plot_surface().

Sources

  • Official BCA syllabus Python Programming, course code 26BCA403SEC01, Unit IV