TExcelTAD
Home › MATLAB / Octave › Plotting Basics

Plotting Basics

Plotting is where MATLAB shines: one call to plot turns two vectors into a figure. This lesson covers the essential line plot; the next lessons add formatting, several plots per figure and other chart types.

How plots work on this site: a figure needs a graphics window, which neither the browser nor the headless Octave used to check these examples has. So each figure is shown in two parts: first the complete plotting code in a plain block (copy it into MATLAB or Octave to see the real figure), then a runnable block with the data part of the same code, whose output is verified, plus a hand-drawn sketch of the figure the plotting code produces. Colours and spacing in the sketch are close to, but not exactly, what MATLAB draws.

Your first plot

plot(x, y) draws a line through the points (x(1), y(1)), (x(2), y(2)), …. The two vectors must have the same length. To draw a smooth curve, simply use many points:

matlab
x = linspace(0, 2*pi, 50);    % 50 points from 0 to 2*pi
y = sin(x);
plot(x, y)
matlab · try it yourself
x = linspace(0, 2*pi, 50);
y = sin(x);
fprintf('%d points, x from %.4f to %.4f\n', numel(x), x(1), x(end));
fprintf('y ranges from %.4f to %.4f\n', min(y), max(y));
50 points, x from 0.0000 to 6.2832
y ranges from -0.9995 to 0.9995

MATLAB opens a figure window and chooses the axis limits automatically. Here the x-axis runs from 0 to 7 because MATLAB rounds limits to "nice" tick values. Notice that y never quite reaches ±1: with 50 points, no sample lands exactly on π/2.

Labels and a title

A plot without labels is hard to read. Add them with title, xlabel and ylabel after calling plot. The '-o' argument draws a line and circle markers at each data point (all the style codes are in the next lesson):

matlab
month = 1:6;
sales = [12 15 11 18 21 19];       % thousands of units
plot(month, sales, '-o')
title('Sales, first half-year')
xlabel('Month')
ylabel('Units (thousands)')
matlab · try it yourself
month = 1:6;
sales = [12 15 11 18 21 19];
[best, m] = max(sales);
fprintf('Total %d, best month %d with %d\n', sum(sales), m, best);
Total 96, best month 5 with 21

Plotting a vector alone

If you pass only one vector, plot(y) uses the index (1, 2, 3, …) as the x-values. That's a quick way to look at a sequence of measurements:

matlab
queue = [3 5 2 6 4 8 7];
plot(queue)
matlab · try it yourself
queue = [3 5 2 6 4 8 7];
disp(1:numel(queue))      % the x-values plot(queue) uses
   1   2   3   4   5   6   7

Plotting a formula

To plot a mathematical function, build the x-vector first and then evaluate the formula element-wise (with .*, ./, .^). Using * or ^ by mistake is the classic plotting error:

matlab
t = 0:0.1:5;
v = 20 * t .* exp(-t);     % .* because t is a vector
plot(t, v)
xlabel('Time (s)')
ylabel('Speed (m/s)')
matlab · try it yourself
t = 0:0.1:5;
v = 20 * t .* exp(-t);
[vmax, k] = max(v);
fprintf('%d samples; peak %.3f m/s at t = %.1f s\n', numel(t), vmax, t(k));
51 samples; peak 7.358 m/s at t = 1.0 s

Figures and closing them

Command Effect
figure Open a new, empty figure window
figure(3) Make figure 3 current (create it if needed)
clf Clear the current figure
close / close all Close the current / every figure
fplot(@(x) sin(x), [0 2*pi]) Plot a function directly, choosing the points for you

Each new plot call replaces the previous plot in the current figure. To keep it and add another line, you need hold on (Multiple Plots lesson).

Tip: In a script, use figure before each plot you want in its own window. Otherwise every plot overwrites the last one and you only see the final figure.

Test yourself

What does plot(y) use as x-values?

  1. Zeros
  2. The indices 1, 2, 3, …
  3. The values of y
  4. It is an error without x

Why write y = x.^2 rather than y = x^2 before plot(x, y)?

  1. .^ is faster
  2. x^2 is a matrix power and fails (or is wrong) for a vector
  3. There is no difference
  4. plot requires dotted operators

Which commands add a title and axis labels?

  1. title, xlabel, ylabel
  2. heading, xaxis, yaxis
  3. label('x'), label('y')
  4. legend