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)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 xx value and a yy 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 xx and yy coordinates of every grid point. np.meshgrid builds the pair.


Python
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 once


With the default 'xy' indexing, which matches MATLAB's meshgrid, rows follow y and columns follow x:


Xij=xj,Yij=yi,Zij=f(xj, yi)X_{ij} = x_j, \qquad Y_{ij} = y_i, \qquad Z_{ij} = f(x_j,\, y_i)


With nxn_x values of xx and nyn_y values of yy, every array has shape (ny,nx)(n_y, n_x) and the grid holds nxnyn_x n_y points. Because NumPy arithmetic is elementwise, writing the formula with X and Y evaluates ff at every grid point without a loop.


Twelve grid points on x and y axes beside a three-row, four-column array, with one point and its array cell highlighted in orange.



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 tt, 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 xyxy-plane and the azimuth is its rotation about the zz-axis. Matplotlib starts at elev=30, azim=-60.

  • elev=90 looks straight down, so the surface reads like a map of zz over the xyxy-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)(n_y, n_x), and Z[i, j] holds f(xj,yi)f(x_j, y_i).
  • 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 nxnyn_x n_y; 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.50 \le x \le 0.5 m and 0≤y≤0.30 \le y \le 0.3 m. A small heater at the corner (0,0)(0, 0) holds a steady temperature field, in degrees Celsius, modelled by


T(x,y)=20+60 e−(x2+y2)/0.05T(x, y) = 20 + 60\, e^{-(x^2 + y^2)/0.05}


with xx and yy in metres. You plot the field with this script:


Python
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:


(ny,nx)=(7,11),nynx=7×11=77(n_y, n_x) = (7, 11), \qquad n_y n_x = 7 \times 11 = 77


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 yy; the second picks the column, which follows xx. Python uses zero-based indexing. Both coordinate arrays step by 0.05 m, so the point is at x4=4(0.05)=0.20 mx_4 = 4(0.05) = 0.20\ \text{m} and y2=2(0.05)=0.10 my_2 = 2(0.05) = 0.10\ \text{m}.


Then x2+y2=0.04+0.01=0.05 m2x^2 + y^2 = 0.04 + 0.01 = 0.05\ \text{m}^2, so the exponent is exactly −1-1 and e−1e^{-1} is approximately ________ to three significant figures. Keeping full precision until the final rounding gives


T=20+60e−1≈42.072766 ∘C≈42.1 ∘CT = 20 + 60e^{-1} \approx 42.072766\ ^\circ\text{C} \approx 42.1\ ^\circ\text{C}


T[2, 4] is the temperature at (0.20 m,0.10 m)(0.20\ \text{m}, 0.10\ \text{m}), which is 42.1 °C. Because this model depends only on x2+y2x^2 + y^2, the swapped point (0.10 m,0.20 m)(0.10\ \text{m}, 0.20\ \text{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 xx, 0.5/0.01=500.5 / 0.01 = 50 intervals, so num is ________; in yy, 0.3/0.01=300.3 / 0.01 = 30 intervals, so num is ________.


nxny=51×31=1581 pointsn_x n_y = 51 \times 31 = 1581 \text{ points}


Each float64 array holds 1581×8=1581 \times 8 = ________, so the three arrays together take


3×12 648=37 944 bytes≈37.9 kB3 \times 12\,648 = 37\,944\ \text{bytes} \approx 37.9\ \text{kB}


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.

Match each method of a Matplotlib 3D axes object to the description of what it draws or does. Assume the axes were created with fig.add_subplot(projection='3d') and that X, Y and Z are grids from np.meshgrid.

Match each term
A.

Sets the camera elevation and azimuth angles in degrees

B.

Joins a sequence of (x, y, z) points with straight segments to trace a curve in space

C.

Draws only the mesh lines of a gridded surface, leaving the cells unfilled

D.

Places a separate marker at each (x, y, z) point without connecting them

E.

Draws filled, shaded quadrilateral patches through gridded height values

F.

Draws level curves along which the height takes chosen constant values

plot_surface

scatter

view_init

plot_wireframe

plot

contour

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A student builds the coordinate grid for a surface plot with the code below, using NumPy's default meshgrid settings.


Python
x = np.linspace(0, 4, 9)
y = np.linspace(-1, 1, 5)
X, Y = np.meshgrid(x, y)


What is X.shape?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A script draws the surface z=sin⁡xcos⁡yz = \sin x \cos y 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. 1.

    Draw the surface and keep its handle with surf = ax.plot_surface(X, Y, Z, cmap='viridis').

  2. 2.

    Create a figure and add axes with projection='3d'.

  3. 3.

    Add a colour bar for the surface with fig.colorbar(surf).

  4. 4.

    Compute the height array Z = np.sin(X) * np.cos(Y) element by element.

  5. 5.

    Display the finished figure with plt.show().

  6. 6.

    Combine x and y into the 2D coordinate grids X and Y with np.meshgrid.

  7. 7.

    Create the 1D coordinate arrays x and y with np.linspace.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice