Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 45 ยท Plotting and Visualization

2-D Plots

Draw 2-D line plots in MATLAB and Octave: plot, line styles, hold on, labels, legend, axis limits, subplot, tiledlayout and saving figures with exportgraphics or print.

A plot is often the fastest way to see whether your numbers make sense. MATLAB and Octave are famous for making this easy: one call to plot turns two vectors into a graph, and a handful of further commands add labels, several curves, multiple panels and a saved image.

MATLAB and Octave are not available in your browser here, so the plotting commands appear as read-only code. Each is paired with a runnable Python/matplotlib TryIt that draws the same picture. matplotlib was in fact designed to feel like MATLAB's plotting, which makes the translation easy. The commands are the same in Octave unless noted.

Anatomy of a figure

Figure The window that holds everything.
Axes The coordinate system with ticks.
Line The curve drawn from your data.
Labels Title, axis names and legend.
1 / 2

Your first plot

plot(x, y) connects the points (x(i), y(i)) with straight lines. The vectors must have the same length. To get a smooth-looking curve, sample the function densely, for example with linspace (see Ranges and Special Matrices).

MATLAB
x = linspace(0, 2*pi, 200);
y = sin(x);
plot(x, y)
xlabel('x (radians)')
ylabel('sin(x)')
title('One period of sine')
grid on

If you give plot only one vector, plot(y), the x values are the indices 1:numel(y). A matrix Y makes one line per column, as in plot(x, Y) where Y has numel(x) rows.

Python A first line plot (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.

Line specifications

A third argument, the line spec, picks color, marker and line style in a compact string. You can also set properties by name.

Piece Examples
Color r red, g green, b blue, k black, m magenta, c cyan
Line style - solid, -- dashed, : dotted, -. dash-dot
Marker o circle, * star, + plus, s square, ^ triangle
MATLAB
plot(x, y, 'r--')                       % red dashed line
plot(x, y, 'ko')                        % black circles, no line
plot(x, y, 'b-s', 'LineWidth', 2, 'MarkerSize', 6)

Markers without a line style ('ko') show only the points, which is the right choice for measurements. A smooth curve should be a line, sampled finely enough that no corners show.

Several curves with hold on

By default each plot call replaces what is on the axes. hold on keeps the existing content so you can add more; hold off returns to the default. You can also pass several pairs in one call. Give each curve a name with legend, in the same order the curves were drawn.

MATLAB
x = linspace(0, 2*pi, 200);
plot(x, sin(x), 'b-', 'LineWidth', 1.5)
hold on
plot(x, cos(x), 'r--', 'LineWidth', 1.5)
plot(pi/2, 1, 'ko', 'MarkerFaceColor', 'k')   % mark a point
hold off
legend('sin', 'cos', 'peak', 'Location', 'southwest')
Python Two curves, a marked point and a legend

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.

One honest difference: matplotlib keeps adding to the current axes by default, so the equivalent of hold on is built in. In MATLAB, forgetting hold on is the usual reason an earlier curve vanishes.

Axes, limits and grids

  • xlim([a b]) and ylim([a b]) set the visible range; axis([xmin xmax ymin ymax]) sets both.
  • axis equal gives both axes the same scale, so circles look round; axis tight fits the data; axis off hides the axes.
  • grid on and box on add light helper lines and a frame.
  • set(gca, 'FontSize', 12) changes properties of the current axes; gca means "get current axes" and gcf "get current figure".
  • xticks, xticklabels and set(gca,'XScale','log') control the tick marks and scaling (MATLAB; in older Octave use set(gca, ...)).
  • figure opens a new window, clf clears the current figure, close all closes every window.

Several panels: subplot and tiledlayout

subplot(rows, cols, index) divides the figure into a grid and selects a cell; indices count along rows from the top left. The newer tiledlayout (MATLAB R2019b and later) manages spacing better: create the layout, then call nexttile for each panel.

MATLAB
t = linspace(0, 1, 300);

subplot(2, 1, 1)
plot(t, sin(2*pi*3*t)); title('3 Hz'); grid on

subplot(2, 1, 2)
plot(t, sin(2*pi*7*t), 'r'); title('7 Hz'); grid on
xlabel('time (s)')

% newer style (MATLAB):
tiledlayout(2, 1)
nexttile; plot(t, sin(2*pi*3*t)); title('3 Hz')
nexttile; plot(t, sin(2*pi*7*t), 'r'); title('7 Hz')

Octave supports subplot; tiledlayout is available only in recent Octave versions, so use subplot for portable scripts.

Python Two stacked panels

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.

Saving a figure

To put a figure in a report, save it to a file instead of taking a screenshot.

MATLAB
exportgraphics(gcf, 'sine.png', 'Resolution', 300);   % MATLAB R2020a and later
print('-dpng', '-r300', 'sine.png');                   % works in MATLAB and Octave
print('-dpdf', 'sine.pdf');                            % vector PDF
saveas(gcf, 'sine.fig');                               % editable MATLAB figure

Prefer a vector format (PDF, SVG, EPS) for papers, since it stays sharp at any zoom, and PNG at 300 dpi for slides and web pages. Run the save command after all labels are added, from a script so the picture can be regenerated whenever the data changes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens if you call plot twice without hold on?

    By default plot clears the axes before drawing. Use hold on to keep earlier curves.
  2. 2. What does the line spec 'r--' mean?

    r is the color red and -- is the dashed line style.
  3. 3. Which call places the second panel of a 2-by-1 layout?

    subplot(rows, cols, index): two rows, one column, and index 2 is the lower panel.
  4. 4. Why might you save a paper figure with print('-dpdf', ...) rather than as a screenshot?

    Vector output stores shapes rather than pixels, so lines and text remain crisp however large the figure is displayed.

Summary

  • plot(x, y) draws a line; sample curves densely with linspace.
  • Line specs like 'r--' or 'ko' set color, style and markers; LineWidth and MarkerSize adjust them.
  • hold on adds curves, legend names them in drawing order, and xlabel, ylabel, title explain the axes.
  • xlim, ylim, axis equal, grid on control the view; gca and gcf refer to the current axes and figure.
  • subplot (portable) or tiledlayout (newer) create several panels.
  • exportgraphics or print save figures; matplotlib TryIts mirror each command, with hold on implicit.

Next, draw other chart types in Bar, Scatter, Histogram and Images.