Table of Contents
Why Use Multiple Plots in One Figure
When you want to compare several related plots, it is often more helpful to place them in the same figure window instead of opening separate figures. MATLAB provides two main approaches for creating grids of plots inside a single figure, the older subplot function and the newer tiledlayout system. In this chapter you focus on how to use both, what their differences are, and when to choose each one.
You already know how to create a basic figure and plot. Here you will extend that knowledge to organize several axes in a structured layout.
The `subplot` Function
The subplot function divides the current figure into a grid of smaller axes. You specify how many rows and columns you want, then which position in that grid you are targeting.
The simplest form is
subplot(m, n, p)
where m is the number of rows, n is the number of columns, and p is the index of the subplot position. The positions are counted row by row from left to right, starting at 1.
For example, to create four plots in a 2 by 2 grid:
x = linspace(0, 2*pi, 200);
subplot(2, 2, 1)
plot(x, sin(x))
subplot(2, 2, 2)
plot(x, cos(x))
subplot(2, 2, 3)
plot(x, sin(2*x))
subplot(2, 2, 4)
plot(x, cos(2*x))
Each call to subplot(2, 2, p) activates the pth axes, so the following plot command draws inside that particular section of the figure.
You can also pass a single three digit number instead of separate arguments. For instance subplot(221) is the same as subplot(2, 2, 1).
Reusing and Clearing Subplots
If you call subplot with the same grid and index more than once, MATLAB returns the same axes. Plotting again will add to that axes unless you clear it.
For example:
subplot(2, 1, 1)
plot(x, sin(x))
subplot(2, 1, 1)
hold on
plot(x, cos(x))
hold offIn this case both sine and cosine appear in the top subplot. If you want to replace the contents instead, you can clear that axes before plotting.
The command
cla
clears the current axes only, while clf clears the entire figure. To clear a specific subplot, you first make it current with subplot and then call cla.
subplot(2, 1, 2)
plot(x, tan(x))
% Later, replace the second subplot
subplot(2, 1, 2)
cla
plot(x, x)
This behaviour is specific to subplot. The newer tiled layout system uses a different pattern for replacement, which you will see later.
Controlling the Subplot Grid
With subplot, the figure region is divided evenly into the specified rows and columns. All subplot axes have the same size and are evenly spaced. If you want one subplot to span multiple grid cells, you can give p as a vector of positions.
For example, a layout with one wide plot on the top and two smaller plots on the bottom can be created like this:
x = linspace(0, 10, 200);
subplot(2, 2, [1 2]) % top row spans columns 1 and 2
plot(x, sin(x))
subplot(2, 2, 3) % bottom left
plot(x, cos(x))
subplot(2, 2, 4) % bottom right
plot(x, sin(x).*cos(x))Here the first subplot uses positions 1 and 2 as a single axes that spans the entire top row. Positions 3 and 4 remain separate at the bottom.
Because subplot always divides the figure into equal cells, you do not have direct control over spacing, margins, or padding. The tiled layout system is more flexible in this respect.
Limits of `subplot` and When It Becomes Awkward
subplot is simple and useful for quick layouts, but it has some limitations that become more visible as your figures grow more complex.
Every time you call subplot, MATLAB searches for matching axes and may adjust positions of other axes to make space. This can cause minor changes in positions and can make fine layout control difficult. Also, managing tight spacing or consistent shared labels is not very convenient with subplot. For simple grids, subplot is usually enough, but for more polished or complex multi-axes figures, the tiled layout system is usually better.
Introduction to `tiledlayout` and `nexttile`
tiledlayout is a newer system designed to replace and improve on subplot. Instead of creating and positioning axes directly, you first create a layout object, then place axes into it with nexttile.
The basic pattern is
t = tiledlayout(m, n);
nexttile
plot(...)
nexttile
plot(...)
The call to tiledlayout(m, n) creates a layout manager that divides the figure into an m by n grid of tiles. Each call to nexttile creates an axes in the next tile, in order from left to right and top to bottom.
For example, the same 2 by 2 grid as before can be created as
x = linspace(0, 2*pi, 200);
tiledlayout(2, 2)
nexttile
plot(x, sin(x))
nexttile
plot(x, cos(x))
nexttile
plot(x, sin(2*x))
nexttile
plot(x, cos(2*x))
This code produces a figure that looks similar to subplot(2,2,...) but internally uses a different system.
Referencing Tiles Explicitly
You are not limited to calling nexttile in strict order. You can specify which tile you want to use, in a similar way to subplot, by giving an index to nexttile.
For example, you can target the second tile directly as
tiledlayout(2, 2)
nexttile(2)
plot(x, cos(x))
If you call nexttile again without an index, MATLAB goes to the next free tile. The order in this case depends on which tiles you have already used.
You can also capture the axes handle returned by nexttile. This lets you adjust properties of that specific axes without making it current:
t = tiledlayout(2, 2);
ax1 = nexttile;
plot(ax1, x, sin(x))
ax2 = nexttile(4);
plot(ax2, x, cos(x))
Here ax1 and ax2 are axes handles associated with tiles 1 and 4.
Spanning Multiple Tiles with `nexttile`
Similar to the way you can supply a vector of indices to subplot, you can make one axes span several tiles by giving nexttile a size argument.
Instead of nexttile(p), you can write
nexttile([r c])
which creates an axes that spans r tile rows and c tile columns, starting at the next free tile. You can also combine a starting index and a span:
nexttile(p, [r c])For example, to create a layout with one large plot on the left and two small plots stacked on the right:
x = linspace(0, 10, 200);
tiledlayout(2, 2)
% Large left plot spans two rows, one column
nexttile(1, [2 1])
plot(x, sin(x))
title('Large plot')
% Top right
nexttile(2)
plot(x, cos(x))
title('Top right')
% Bottom right
nexttile(4)
plot(x, sin(x).*cos(x))
title('Bottom right')The axes in the first tile now covers the left half of the figure, and the two others are stacked on the right.
Controlling Spacing and Padding
One of the main advantages of tiledlayout over subplot is that you can control the spacing between tiles and the padding around the outer edges.
When you create a layout, tiledlayout returns an object. You can store it, then set its properties.
For example:
t = tiledlayout(2, 2);
t.TileSpacing = 'compact';
t.Padding = 'compact';
nexttile
plot(x, sin(x))
nexttile
plot(x, cos(x))
nexttile
plot(x, sin(2*x))
nexttile
plot(x, cos(2*x))
The TileSpacing property controls the space between tiles. It can take values like 'normal', 'compact', or 'none'. The Padding property controls the margins around the outside of the grid. 'compact' and 'none' are useful when you want the plots to sit close together.
You can also change these properties after plotting. The layout automatically adjusts the positions of all tiles.
Adding a Shared Title for the Layout
With subplot, each axes can have its own title, but there is no built in way to add a single title for the entire figure that automatically aligns with the grid. The tiledlayout object includes a Title property that provides a shared title for the whole layout.
You can set it using the title function, but this time applying it to the layout instead of a single axes.
For example:
x = linspace(0, 2*pi, 200);
t = tiledlayout(2, 2);
t.TileSpacing = 'compact';
title(t, 'Trigonometric functions')
nexttile
plot(x, sin(x))
title('sin(x)')
nexttile
plot(x, cos(x))
title('cos(x)')
nexttile
plot(x, sin(2*x))
title('sin(2x)')
nexttile
plot(x, cos(2*x))
title('cos(2x)')
Here the call title(t, 'Trigonometric functions') creates a single overall title above the grid. Each individual axes still has its own title as well.
There are similar functions for shared x and y labels, xlabel(t, '...') and ylabel(t, '...'), which label the entire layout rather than a single axes.
Linking Axes in a Tiled Layout
When comparing several plots that share the same x or y range, it can be convenient to zoom or pan in one axes and have the others follow. You can do this by linking axes. Although this feature is not unique to tiledlayout, you often use it together with tiled layouts.
After creating all axes, you can link them with linkaxes. In a tiled layout, you typically collect the axes when you call nexttile.
For example:
x = linspace(0, 10, 1000);
t = tiledlayout(3, 1);
ax1 = nexttile;
plot(ax1, x, sin(x))
ax2 = nexttile;
plot(ax2, x, sin(2*x))
ax3 = nexttile;
plot(ax3, x, sin(3*x))
linkaxes([ax1 ax2 ax3], 'x')Now, when you zoom in on the x axis in one subplot, the other two follow automatically. This is particularly useful with stacked time series or related signals.
Mixing Regular Axes and Tiled Layouts
In a single figure, you should not mix subplot with tiledlayout because they both try to manage axes positions and may interfere with each other. However, you can still create extra axes manually using axes in the same figure as a tiled layout, as long as you understand that the layout will not control these extra axes.
In basic beginner use, it is usually best to choose one system subplot or tiledlayout for each figure and stick with it.
If you use tiledlayout, let it own the grid of plots, and only consider manual axes if you have a special reason.
When to Use `subplot` vs `tiledlayout`
For quick, throwaway figures where appearance and spacing do not matter much, subplot is often simpler to type and easier to remember. It is also compatible with much older versions of MATLAB. For more polished layouts, especially where you need control over spacing, shared titles, or spanning multiple tiles, tiledlayout is the better choice.
If you start a new project and you have a recent version of MATLAB, it is a good idea to use tiledlayout as your default multi plot tool and fall back to subplot only when you need to work with old code or follow older examples.
Important points to remember:
subplot(m, n, p)divides the figure into anmbyngrid and activates positionp. Positions are numbered row by row, left to right.tiledlayout(m, n)withnexttileis the modern way to create multi plot layouts and allows control of spacing usingTileSpacingandPadding.- You can span multiple cells with
subplot(…, [indices])and withnexttile(start, [rows cols])in a tiled layout. - Use
title(t, ...),xlabel(t, ...), andylabel(t, ...)with atiledlayoutobject to create shared titles and labels for the entire grid. - Avoid mixing
subplotandtiledlayoutin the same figure. Choose one layout method per figure for predictable results.