TExcelTAD
Home › MATLAB / Octave › 3-D Plots

3-D Plots

A 2-D plot answers "how does y change with x?". Many real problems have a third coordinate: the path of a drone, the position of stars, a measurement taken at different temperatures and pressures. MATLAB's 3-D functions work like their 2-D cousins with one more input, and every 3-D axes can be turned to look at the data from any direction.

As in the earlier plotting lessons, each figure shows the full plotting code first (figures need a graphics window, so that code doesn't run in this browser), then a runnable part that computes the numbers behind the picture, and a sketch of the result.

Function Draws 2-D cousin
plot3(x, y, z) A line (or markers) through points in space plot
scatter3(x, y, z, s, c) Separate markers, optionally sized and coloured per point scatter
stem3(x, y, z) Vertical stems from the xy-plane up to each value stem
quiver3(x, y, z, u, v, w) Arrows (vectors) starting at each point quiver
mesh, surf, contour3 Surfaces over a grid (next lesson) contour
bar3(M) 3-D bar chart of a matrix (MATLAB only; Octave 11 lacks it) bar

Lines in space: plot3

plot3 takes three vectors of the same length and joins the points (x(k), y(k), z(k)) in order. It accepts the same line specs and name-value pairs as plot (see Plot Formatting), and zlabel and zlim complete the familiar xlabel/xlim family. A helix is the classic example: a circle in x and y while z climbs steadily:

matlab
t = linspace(0, 4*pi, 200);          % two full turns
x = cos(t);
y = sin(t);
z = t / (2*pi);                      % rises by 1 per turn
plot3(x, y, z, 'LineWidth', 1.5)
grid on
xlabel('x'); ylabel('y'); zlabel('z')
title('Helix')
matlab · try it yourself
t = linspace(0, 4*pi, 200);
x = cos(t);
y = sin(t);
z = t / (2*pi);
L = sum(sqrt(diff(x).^2 + diff(y).^2 + diff(z).^2));   % length of the polyline
fprintf('%d points, z from %g to %g\n', numel(t), min(z), max(z));
fprintf('Curve length: %.2f (exact: %.2f)\n', L, 2*sqrt(4*pi^2 + 1));
200 points, z from 0 to 2
Curve length: 12.72 (exact: 12.72)

Unlike plot, a 3-D plot starts with the grid off in MATLAB, and the axes box shows only the three back planes. grid on draws grid lines on those planes, which makes depth much easier to judge. box on adds the front edges of the box as well.

Note: plot3(x, y, z) with matrices draws one line per column, exactly like plot. Add hold on to combine several 3-D objects in one axes.

Choosing the viewpoint: view

A 3-D axes is seen from a viewpoint given by two angles:

  • azimuth (az): rotation around the vertical z-axis, in degrees. 0 means you look from the negative y side towards the xz-plane.
  • elevation (el): how far above the xy-plane you are. 90 means looking straight down.
Call Viewpoint
view(3) Default 3-D view: az = -37.5, el = 30
view(2) Straight down from above (az = 0, el = 90), a normal 2-D plot
view(az, el) or view([az el]) Any angle you like
[az, el] = view Read back the current angles
rotate3d on Drag with the mouse to turn the plot interactively
matlab
t = linspace(0, 4*pi, 200);
for k = 1:3
    subplot(1, 3, k)
    plot3(cos(t), sin(t), t/(2*pi), 'LineWidth', 1.2)
    grid on
end
subplot(1, 3, 1); view(3);     title('view(3)')
subplot(1, 3, 2); view(2);     title('view(2)')
subplot(1, 3, 3); view(0, 0);  title('view(0, 0)')

Looking down from the top (view(2)), the helix is just a circle; from the side (view(0, 0), i.e. from the negative y side at zero elevation) it becomes a cosine wave climbing up the z-axis.

What view does is a simple projection. For azimuth a and elevation e, a point p lands at screen coordinates right·p and up·p, where right = [cos a, sin a, 0] and up = [-sin e·sin a, sin e·cos a, cos e]. MATLAB's viewmtx(az, el) returns this matrix (Octave 11 lacks viewmtx), but a few lines reproduce it and show where each axis points in the default view:

matlab · try it yourself
az = -37.5; el = 30;
right = [cosd(az), sind(az), 0];
up = [-sind(el)*sind(az), sind(el)*cosd(az), cosd(el)];
names = 'xyz';
E = eye(3);                      % unit vectors along x, y and z
for k = 1:3
    fprintf('%s axis -> screen (%5.2f, %5.2f)\n', names(k), right*E(:, k), up*E(:, k));
end
x axis -> screen ( 0.79,  0.30)
y axis -> screen (-0.61,  0.40)
z axis -> screen ( 0.00,  0.87)

So in the default view you look from the corner where x and y are smallest: increasing x runs to the right (and a little up the screen), increasing y runs to the left and up, and z points straight up, which matches the box in the helix sketch. cosd and sind take angles in degrees, which saves a conversion with deg2rad.

Points in space: scatter3

scatter3(x, y, z) draws unconnected markers. The fourth and fifth inputs set marker size (in points squared) and colour; passing a vector as the colour maps each value through the current colormap, so a fourth variable can be shown as colour. Here, a small experiment measured the yield of a reaction at different temperatures and pressures:

matlab
temp  = [20 20 20 40 40 40 60 60 60];      % deg C
press = [1 2 3 1 2 3 1 2 3];               % bar
yield = [52 58 61 63 71 75 60 69 72];      % percent
scatter3(temp, press, yield, 60, yield, 'filled')
xlabel('Temperature (\circC)'); ylabel('Pressure (bar)'); zlabel('Yield (%)')
colorbar
grid on
matlab · try it yourself
temp  = [20 20 20 40 40 40 60 60 60];
press = [1 2 3 1 2 3 1 2 3];
yield = [52 58 61 63 71 75 60 69 72];
[best, k] = max(yield);
fprintf('Best yield %d%% at %d degC and %d bar\n', best, temp(k), press(k));
fprintf('Mean yield per pressure: %s\n', mat2str(accumarray(press', yield', [], @mean)', 4));
Best yield 75% at 40 degC and 3 bar
Mean yield per pressure: [58.33 66 69.33]

Points floating in space are hard to place precisely. stem3(temp, press, yield) drops a line from each point to the floor, which helps the eye; turning the view with rotate3d helps even more.

Arrows in space: quiver3

quiver3(x, y, z, u, v, w) draws an arrow from each point (x, y, z) in the direction (u, v, w). It's how you show velocities, forces or surface normals. The arrows are scaled automatically to avoid overlapping; quiver3(..., 0) turns the scaling off so each arrow has its true length.

matlab
t = linspace(0, 2*pi, 9);  t(end) = [];      % 8 points on a circle
x = cos(t); y = sin(t); z = zeros(size(t));
u = -sin(t); v = cos(t); w = 0.5 * ones(size(t));   % tangent, tilted upwards
quiver3(x, y, z, u, v, w, 0)
axis equal; grid on
matlab · try it yourself
t = linspace(0, 2*pi, 9);  t(end) = [];
x = cos(t); y = sin(t);
u = -sin(t); v = cos(t);
dots = x .* u + y .* v;          % position . direction in the xy-plane
fprintf('Largest |dot product|: %.4f (the arrows are tangent)\n', max(abs(dots)));
fprintf('Arrow length: %.4f\n', norm([u(1) v(1) 0.5]));
Largest |dot product|: 0.0000 (the arrows are tangent)
Arrow length: 1.1180

Axis scaling in 3-D

By default MATLAB stretches each axis so the data fills a box of fixed shape, which is why the helix looks tall even though it is only 2 units high. Three commands control this:

Command Effect
axis equal One unit has the same length on all three axes (a circle looks round)
axis tight Limits fit the data exactly, without padding
daspect([1 1 0.5]) Custom data aspect ratio: here z units are drawn half as long
xlim, ylim, zlim Set each range explicitly

Use axis equal whenever the coordinates are lengths in the same unit (positions, geometry); leave the default stretching when the axes measure different things, as in the temperature/pressure/yield example.

Summary

  • plot3, scatter3, stem3 and quiver3 are the 3-D versions of plot, scatter, stem and quiver; they add z (and w) inputs and work with zlabel, zlim and hold on.
  • view(az, el) chooses the viewpoint: view(3) is the default (−37.5°, 30°) and view(2) looks straight down.
  • grid on, box on and axis equal make depth and proportions easier to read.

Next, Surfaces & Contours draws functions of two variables over a grid. Learn more: the same ideas in Python are in Matplotlib 3-D plots.

Test yourself

Which call draws a line through the points (x(k), y(k), z(k))?

  1. plot(x, y, z)
  2. plot3(x, y, z)
  3. line3(x, y, z)
  4. surf(x, y, z)

What does view(2) do to a 3-D plot?

  1. Zooms in by a factor of 2
  2. Shows two copies side by side
  3. Looks straight down from above (azimuth 0, elevation 90)
  4. Restores the default 3-D view

In scatter3(x, y, z, 60, yield, 'filled'), what does the vector yield control?

  1. Marker size
  2. Marker colour, through the colormap
  3. The z-coordinates
  4. The transparency