Creating Specialized and Three Dimensional Plots
Three-Dimensional Plotting: Grids, Surfaces and Views
Many quantities depend on two inputs at once: the temperature across a heated plate, the height of terrain, or the error of a model as two parameters vary. A line plot shows one slice of such a relation; a three-dimensional plot shows the whole surface z=f(x,y), or traces a curve through space. In Matplotlib the drawing call is short. The real work is building data of the right shape and choosing a view that shows the feature you care about.
Sampling a function on a grid
A surface needs a height at every combination of an x value and a y value. You start with two 1D arrays of sample coordinates and expand them into a coordinate grid: a pair of 2D arrays X and Y whose entries hold the x and y coordinates of every grid point. np.meshgrid builds the pair.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-2, 2, 41) # 41 x values
y = np.linspace(-1, 1, 21) # 21 y values
X, Y = np.meshgrid(x, y) # X.shape == Y.shape == (21, 41)
Z = X * np.exp(-X**2 - Y**2) # evaluated at all 861 points at onceWith the default 'xy' indexing, which matches MATLAB's meshgrid, rows follow y and columns follow x:
With nx values of x and ny values of y, every array has shape (ny,nx) and the grid holds nxny points. Because NumPy arithmetic is elementwise, writing the formula with X and Y evaluates f at every grid point without a loop.
The number of points grows as the product of the two counts. Doubling both sample counts quadruples the array entries and, for a fixed data type, their payload memory. Drawing time depends on downsampling, rendering paths and overhead as well as grid size. Example: a 100 by 100 grid has 10 000 points; each array of float64 values then takes 80 000 bytes, so X, Y and Z together need 240 kB.
Matching the plot type to the data
Create 3D axes with ax = fig.add_subplot(projection='3d'), then choose the method by the shape of your data.
Method | Data it takes | Best for |
|---|---|---|
ax.plot_surface(X, Y, Z, cmap='viridis') | three 2D grids of equal shape | smooth fields, with colour showing height |
ax.plot_wireframe(X, Y, Z) | three 2D grids of equal shape | seeing the mesh and the parts a filled surface hides |
ax.contour(X, Y, Z) | three 2D grids of equal shape | level curves, drawn at their heights on 3D axes |
ax.plot(x, y, z) | three 1D arrays of equal length | a connected curve in space, such as a trajectory |
ax.scatter(x, y, z) | three 1D arrays of equal length | unconnected measured points |
Data on a grid suits the first three methods; data along a single path suits the last two. A parametric curve gives all three coordinates as functions of one parameter t, so x, y and z are 1D arrays of the same length and no grid is needed. Example: with t = np.linspace(0, 4*np.pi, 200), the call ax.plot(np.cos(t), np.sin(t), t/(2*np.pi)) draws a helix of radius 1 that rises 1 unit per turn and completes two turns.
Choosing the viewpoint
A 3D plot is a 2D projection, so the camera position decides what is hidden. ax.view_init(elev, azim) sets it in degrees: the elevation is the camera's angle above the xy-plane and the azimuth is its rotation about the z-axis. Matplotlib starts at elev=30, azim=-60.
- elev=90 looks straight down, so the surface reads like a map of z over the xy-plane.
- elev=0 looks edge-on and shows a side profile of the surface.
- Intermediate elevations of 20° to 40° show both height and layout, but a tall peak can hide a valley behind it.
Check a surface from at least two angles before drawing conclusions from it. In an interactive window you can drag the axes to rotate them, then read the chosen angles from ax.elev and ax.azim to reproduce the view in a script.
What to remember
- np.meshgrid(x, y) returns grids of shape (ny,nx), and Z[i, j] holds f(xj,yi).
- Surfaces, wireframes and contours take 2D grids; 3D plot and scatter take equal-length 1D arrays.
- Point count and payload memory for a fixed data type scale with nxny; drawing time also depends on downsampling, rendering paths and overhead.
- view_init(elev, azim) sets the camera; check more than one angle.
Example: Surface plot of a heated plate
A thin steel plate occupies 0≤x≤0.5 m and 0≤y≤0.3 m. A small heater at the corner (0,0) holds a steady temperature field, in degrees Celsius, modelled by
with x and y in metres. You plot the field with this script:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 0.5, 11)
y = np.linspace(0, 0.3, 7)
X, Y = np.meshgrid(x, y)
T = 20 + 60 * np.exp(-(X**2 + Y**2) / 0.05)
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.plot_surface(X, Y, T, cmap='inferno')
ax.set_xlabel('x (m)')
ax.set_ylabel('y (m)')
ax.set_zlabel('T (°C)')
plt.show()a) What shape do X, Y and T have, and how many grid points does the surface pass through?
np.linspace(0, 0.5, 11) includes both endpoints, so its 11 values are separated by 10 intervals of ________. np.linspace(0, 0.3, 7) gives 7 values with the same spacing.
With the default 'xy' indexing, rows follow y and columns follow x, so each array has ________ rows and 11 columns:
X, Y and T each have shape (7, 11), and the surface passes through 77 grid points. Writing (11, 7) is the usual slip: that is the 'ij' layout, not what this script produces.
b) Which point of the plate does T[2, 4] describe, and what temperature does it hold?
The first index picks the row, which follows y; the second picks the column, which follows x. Python uses zero-based indexing. Both coordinate arrays step by 0.05 m, so the point is at x4=4(0.05)=0.20 m and y2=2(0.05)=0.10 m.
Then x2+y2=0.04+0.01=0.05 m2, so the exponent is exactly −1 and e−1 is approximately ________ to three significant figures. Keeping full precision until the final rounding gives
T[2, 4] is the temperature at (0.20 m,0.10 m), which is 42.1 °C. Because this model depends only on x2+y2, the swapped point (0.10 m,0.20 m) happens to have the same temperature, but it is a different location; for a field without this symmetry, swapping the indices would also give the wrong value.
c) To smooth the surface, you change the num arguments so that the spacing is 0.01 m in both directions. How many grid points does the new surface have, and how much memory do X, Y and T occupy together if each float64 value uses 8 bytes?
Because linspace includes both endpoints, num is the number of intervals plus one. In x, 0.5/0.01=50 intervals, so num is ________; in y, 0.3/0.01=30 intervals, so num is ________.
Each float64 array holds 1581×8= ________, so the three arrays together take
The 51 columns exceed plot_surface's default ccount of 50, so the default column stride becomes 2. Surface patches therefore span two column intervals, with intermediate vertices along their perimeters retained; this does not simply discard every second column. Pass rcount=31, ccount=51 to use a patch for every grid cell.
The refined grid has 1581 points, about 20.5 times the original 77. The combined data payload of X, Y and T is 37,944 bytes, or about 37.9 kB, excluding array-object overhead and plotting memory.
A student builds the coordinate grid for a surface plot with the code below, using NumPy's default meshgrid settings.
x = np.linspace(0, 4, 9)
y = np.linspace(-1, 1, 5)
X, Y = np.meshgrid(x, y)What is X.shape?
A script draws the surface z=sinxcosy with Matplotlib and adds a colour bar. It follows the common convention of preparing all of the numerical data before creating any figure objects. Put the steps of the script in the order they must run.
1.
Draw the surface and keep its handle with surf = ax.plot_surface(X, Y, Z, cmap='viridis').
2.
Create a figure and add axes with projection='3d'.
3.
Add a colour bar for the surface with fig.colorbar(surf).
4.
Compute the height array Z = np.sin(X) * np.cos(Y) element by element.
5.
Display the finished figure with plt.show().
6.
Combine x and y into the 2D coordinate grids X and Y with np.meshgrid.
7.
Create the 1D coordinate arrays x and y with np.linspace.