Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 45 ยท Plotting and Visualization

3-D Plots, Surfaces and Contours

Draw 3-D curves, surfaces and contour maps in MATLAB and Octave with plot3, meshgrid, surf, mesh, contour, view and colorbar, plus runnable matplotlib stand-ins.

Some data has three coordinates: a path through space, or a height that depends on two inputs. MATLAB and Octave draw both with a small family of commands. plot3 draws a curve in 3-D, surf and mesh draw a surface z = f(x, y), and contour shows the same surface as a flat map of level lines.

MATLAB and Octave are not available in your browser here, so the MATLAB commands are read-only. Each one is paired with a runnable Python/matplotlib TryIt that draws the same picture. The commands are identical in Octave unless noted. If you have not met 2-D plotting yet, read 2-D Plots first.

Pick the right 3-D tool

plot3 A curve through space.
surf A shaded surface z = f(x, y).
mesh The same surface as a wireframe.
contour Level lines on a flat map.
1 / 2

Curves in space with plot3

plot3(x, y, z) is plot with a third vector. The three vectors must have the same length, and the points are joined in order. A helix is the classic example: x and y trace a circle while z climbs steadily.

MATLAB
t = linspace(0, 6*pi, 400);
plot3(cos(t), sin(t), t, 'LineWidth', 1.5)
xlabel('x'); ylabel('y'); zlabel('height')
title('A helix')
grid on

A 3-D plot has a z axis, so add zlabel next to xlabel and ylabel. axis equal keeps the circle round, and axis tight trims empty space.

Python A helix with plot3 (matplotlib stand-in)

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 MATLAB every axes can show 3-D content, so there is no special axes to create. matplotlib needs projection="3d" once; that is the main structural difference.

Surfaces need a grid: meshgrid

A surface is defined by a height at every point of a rectangular grid. You rarely type that grid by hand. Give meshgrid the x values and the y values, and it returns two matrices of the same size: X repeats the x vector down the rows, Y repeats the y vector across the columns.

MATLAB
x = -2:1:2;           % 5 values
y = 1:3;              % 3 values
[X, Y] = meshgrid(x, y)
% X =
%   -2  -1   0   1   2
%   -2  -1   0   1   2
%   -2  -1   0   1   2
% Y =
%    1   1   1   1   1
%    2   2   2   2   2
%    3   3   3   3   3

X(i,j) and Y(i,j) are now the coordinates of grid point (i,j). Any expression using element-wise operators then gives the heights for the whole grid at once, which is vectorization at work (see Arithmetic: Matrix vs Element-wise). Remember the dots: X.^2 + Y.^2, not X^2 + Y^2.

Python What meshgrid returns

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 the shape: 3 rows (one per y value) and 5 columns (one per x value). Rows follow y and columns follow x, which surprises many beginners.

surf and mesh

surf(X, Y, Z) draws the surface as colored patches, with the color following the height. mesh(X, Y, Z) draws only the grid lines. Both take the grid from meshgrid.

MATLAB
[X, Y] = meshgrid(linspace(-3, 3, 60));      % one vector: used for both axes
Z = sin(sqrt(X.^2 + Y.^2));                  % ripples around the origin
surf(X, Y, Z)
shading interp                               % smooth colors, no black grid lines
colormap parula                              % MATLAB default; use viridis in Octave
colorbar
xlabel('x'); ylabel('y'); zlabel('z')
title('Ripples')

shading interp blends colors across each patch and hides the grid lines, which looks better on a fine grid; shading flat gives one color per patch. colorbar adds a legend that maps colors to values. If you only have x and y vectors and no grid, surf(x, y, Z) also works, where Z has numel(y) rows and numel(x) columns.

Python A rippled surface with a colorbar

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.

A wireframe is one call away: mesh(X, Y, Z) in MATLAB, ax.plot_wireframe(X, Y, Z) in matplotlib. Use it when you want to see the grid itself, for example to check that the sampling is dense enough.

Looking from another angle: view

A surface can hide features behind itself. view(azimuth, elevation) sets the camera in degrees: azimuth rotates around the vertical axis and elevation lifts the camera above the floor. The MATLAB default is view(-37.5, 30). view(2) looks straight down (a top view) and view(3) restores the default 3-D view. In a MATLAB figure window you can also drag with the rotate tool.

MATLAB
view(45, 20)     % turn the camera and lower it a little
view(2)          % top-down, like a map
Python The same surface from three viewpoints

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.

Careful with the argument order: MATLAB's view(azimuth, elevation) is the reverse of matplotlib's view_init(elev, azim).

Contour maps

A contour plot shows lines of equal height, like the elevation lines on a hiking map. It is often easier to read exact values from a contour plot than from a surface, and nothing hides behind anything.

MATLAB
[X, Y] = meshgrid(linspace(-2, 2, 80));
Z = X .* exp(-X.^2 - Y.^2);
contour(X, Y, Z, 15)        % 15 levels
colorbar
axis equal
title('Contour lines')

contourf(X, Y, Z, 15)       % filled bands instead of lines
surfc(X, Y, Z)              % surface with contours underneath

The fourth argument is either a number of levels or a vector of exact levels such as [-0.2 0 0.2]. clabel (with the handle returned by contour) writes the value on the lines. Choose a perceptually even colormap; avoid rainbow-style maps for quantitative data, because they invent edges that are not in the data.

Python Contour lines and filled contours

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.

Practical tips

  • Keep the grid moderate. A 100 by 100 grid is 10,000 points and renders instantly; 2,000 by 2,000 is four million and can make the window crawl.
  • Use element-wise operators (.*, ./, .^) when computing Z from X and Y. A missing dot gives either a wrong picture or a dimension error.
  • To cut a hole in a surface, set those heights to NaN; they are not drawn.
  • scatter3(x, y, z) draws unconnected points, useful for 3-D measurements (see Bar, Scatter, Histogram and Images for the 2-D version).
  • Save the figure the same way as any other (exportgraphics, print). Pick the view first, because the saved picture is exactly what is on screen.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What do the two outputs of [X, Y] = meshgrid(x, y) contain?

    X(i,j) and Y(i,j) hold the coordinates of grid point (i,j), so any formula in X and Y yields the heights for the whole grid at once.
  2. 2. If x has 5 elements and y has 3, what size is X from meshgrid(x, y)?

    Rows follow y (3) and columns follow x (5), so X is 3-by-5.
  3. 3. Which expression correctly builds the heights of a cone from X and Y?

    Element-wise powers are needed. X^2 on a non-square matrix is an error, and on a square one it means matrix multiplication.
  4. 4. What does view(2) do?

    view(2) selects the 2-D top view, similar to a contour map. view(3) restores the default 3-D view.
  5. 5. Why is a contour plot sometimes better than surf?

    A surface can hide features behind peaks, while level lines show every region of the grid at once.

Summary

  • plot3(x, y, z) draws a curve in space; add zlabel for the third axis.
  • meshgrid turns x and y vectors into coordinate matrices; rows follow y, columns follow x.
  • Compute Z with element-wise operators, then draw with surf (patches) or mesh (wireframe); shading interp and colorbar polish the result.
  • view(azimuth, elevation) moves the camera; matplotlib's view_init takes the arguments in the opposite order.
  • contour and contourf show level lines or bands on a flat map.
  • The matplotlib TryIts mirror each command; MATLAB itself is not run on this site.

Next, move from pictures to data on disk in Reading and Writing Files.