Written and maintained by CASRAI Editorial Board
Last updated
What it is used for in research
In academic research and scientific reporting, figures frequently require presenting multiple related datasets side by side. Researchers use multi-panel figures—created using matlab subplots or modern tiled chart layouts—to align time-series measurements across multiple sensor channels, contrast experimental treatment groups with control cohorts, or display parametric sweeps across varying physical conditions. Creating a coherent subplot matlab layout enables peer reviewers and readers to compare trends across identical time windows or spatial scales without flipping between separate figures.
Historically, the built-in subplot function has served as MATLAB’s standard mechanism for dividing a graphics figure window into a regular rectangular grid of Cartesian axes. Starting in MATLAB R2019b, MathWorks introduced tiledlayout and nexttile as a more flexible and customizable alternative designed specifically to eliminate the formatting drawbacks of traditional subplots, such as excessive whitespace and overlapping axis annotations. Understanding both legacy subplot indexing and modern tiledlayout workflows allows investigators to maintain existing laboratory analysis scripts while adopting publication-grade figure formatting for manuscripts submitted to peer-reviewed journals.
For complementary visualization fundamentals, consult our guide on MATLAB graph plotting fundamentals, learn how to manage figure palettes in MATLAB plot color and styling, or structure input datasets using MATLAB data tables.
Install or access (official source only)
Both subplot and tiledlayout are core graphical components built directly into base MATLAB; they require no separate toolboxes or third-party add-ons. Researchers can access these plotting capabilities through two official MathWorks distribution channels:
- MATLAB Desktop Application: Installed locally on 64-bit Windows, macOS, or Linux through the official MathWorks installer available from the MathWorks website (
mathworks.com). Licensing is managed via individual MathWorks accounts, campus-wide academic licenses, or organizational concurrent network licenses. - MATLAB Online: Available directly within modern web browsers at
matlab.mathworks.com. MATLAB Online provides an identical graphical plotting engine and figure renderer hosted in MathWorks Cloud infrastructure, fully supporting bothsubplotandtiledlayout.
Version Compatibility:
- Legacy
subplot(m, n, p)andlinkaxesare available across all modern and legacy versions of MATLAB. - The
tiledlayoutcontainer,nexttilefunction, and high-resolutionexportgraphicscommand require MATLAB R2019b or later. - The
sgtitlefunction for subplot grid titles requires MATLAB R2018b or later.
Step-by-step task (numbered, with menu names or commands exactly as in the current docs)
Task 1: Creating a Standard Subplot Grid with subplot(m, n, p)
A standard matlab subplot example uses a 1-based indexing scheme where grid positions are numbered row by row from top-left to bottom-right. Follow these numbered steps to generate a 2×2 grid of subplots:
- Initialize the figure: Open a fresh figure window and specify physical dimensions suited for single-column or double-column journal presentation.
- Create the first subplot: Call
subplot(2, 2, 1)to partition the figure canvas into 2 rows and 2 columns, directing subsequent plotting commands to the first tile (row 1, column 1). - Generate the plot and label the axes: Execute your plotting function (such as
plotorscatter) and define panel titles and axis labels. - Advance through remaining tiles: Repeat the command for positions 2, 3, and 4 (
subplot(2, 2, 2),subplot(2, 2, 3),subplot(2, 2, 4)). - Add a centered overall figure title: Apply MATLAB subplot titles to individual panels with
title(...), and add a global super-title spanning the entire figure canvas usingsgtitle(...).
% Task 1: 2x2 Subplot Grid
fig = figure('Color', 'w');
% Subplot 1 (Top-Left)
subplot(2, 2, 1);
x = linspace(0, 10, 100);
plot(x, sin(x), 'b-', 'LineWidth', 1.5);
title('Panel A: Raw Signal');
xlabel('Time (s)');
ylabel('Amplitude (V)');
grid on;
% Subplot 2 (Top-Right)
subplot(2, 2, 2);
plot(x, cos(x), 'r--', 'LineWidth', 1.5);
title('Panel B: Quadrature Phase');
xlabel('Time (s)');
ylabel('Amplitude (V)');
grid on;
% Subplot 3 (Bottom-Left)
subplot(2, 2, 3);
plot(x, sin(2*x), 'k:', 'LineWidth', 1.5);
title('Panel C: Harmonic 2x');
xlabel('Time (s)');
ylabel('Amplitude (V)');
grid on;
% Subplot 4 (Bottom-Right)
subplot(2, 2, 4);
plot(x, cos(2*x), 'm-.', 'LineWidth', 1.5);
title('Panel D: Harmonic Cosine');
xlabel('Time (s)');
ylabel('Amplitude (V)');
grid on;
% Centered figure super-title
sgtitle('Experimental Waveform Analysis', 'FontSize', 12, 'FontWeight', 'bold');
Task 2: Modern Multi-Panel Layouts with tiledlayout and nexttile
For manuscripts requiring tight spacing and shared labels, MathWorks recommends tiledlayout over legacy subplot. This method easily accommodates matlab subplots of different sizes and enables a single panel to span multiple columns:
- Instantiate the layout object: Call
t = tiledlayout(m, n)with configuration optionsTileSpacingandPadding. Setting both to'compact'or'tight'minimizes wasted margins between panels (MATLAB subplot tight). - Navigate sequentially using nexttile: Call
nexttileto advance to the next available position and return the active axes handle. - Create spanning panels: To span a panel across multiple rows or columns (matlab subplot span multiple columns), pass a two-element span vector
nexttile([rows, cols]). For example,nexttile([1, 2])spans 1 row and 2 columns. - Apply shared layout labels: Instead of attaching labels to individual axes, pass the layout object
tdirectly totitle(t, ...),xlabel(t, ...), andylabel(t, ...)(Matlab subplot labels).
% Task 2: Asymmetric Layout with Spanning Tiles
fig = figure('Units', 'centimeters', 'Position', [5, 5, 17.5, 12], 'Color', 'w');
t = tiledlayout(2, 2, 'TileSpacing', 'compact', 'Padding', 'compact');
% Panel 1: Spanning both columns on the top row
ax1 = nexttile([1, 2]);
t_time = linspace(0, 1, 1000);
signal = sin(2*pi*50*t_time) + 0.5*randn(size(t_time));
plot(ax1, t_time, signal, 'Color', [0.2 0.2 0.2]);
title(ax1, '(a) Continuous Time-Series Overview');
ylabel(ax1, 'Voltage (mV)');
grid(ax1, 'on');
% Panel 2: Bottom-left sub-region detail
ax2 = nexttile;
plot(ax2, t_time(1:100), signal(1:100), 'b-', 'LineWidth', 1.2);
title(ax2, '(b) Transient Zoom (0-100 ms)');
ylabel(ax2, 'Voltage (mV)');
grid(ax2, 'on');
% Panel 3: Bottom-right frequency spectrum
ax3 = nexttile;
f = linspace(0, 250, 100);
power = exp(-((f - 50)/15).^2);
plot(ax3, f, power, 'r-', 'LineWidth', 1.2);
title(ax3, '(c) Power Spectral Density');
xlabel(ax3, 'Frequency (Hz)');
ylabel(ax3, 'Power (dB/Hz)');
grid(ax3, 'on');
% Shared layout labeling
title(t, 'Sensor Performance and Harmonic Response', 'FontSize', 12);
xlabel(t, 'Time Domain Reference (s)');
Task 3: Synchronizing Shared Axes and Publication Export
Stacked scientific figures often share a common time or frequency axis. Using linkaxes aligns data ranges and prevents misaligned scales (MATLAB subplot share y axis or x axis):
- Capture axes handles: Assign the axes returned by
nexttileorsubplotto variables (for example,ax1 = nexttile;andax2 = nexttile;). - Synchronize axes limits: Call
linkaxes([ax1, ax2], 'x')to lock the horizontal zoom and pan across both panels. Use'y'to share vertical axes or'xy'for bidirectional synchronization. - Suppress interior tick labels: To prevent redundant numerical labels between vertically stacked plots, set the upper axis tick labels to empty:
ax1.XTickLabel = {};. - Set exact print dimensions: Journal author guidelines dictate single-column widths (typically 8.5 cm) or double-column widths (typically 17.5 cm). Configure
fig.Units = 'centimeters'and set the width and height explicitly (MATLAB subplot size). - Export with exportgraphics: Export vector artwork (PDF or EPS) or high-resolution raster images (300 DPI PNG or TIFF) without figure window border artifacts.
% Task 3: Shared Stacked Axes with Publication Sizing
fig = figure('Units', 'centimeters', 'Position', [5, 5, 8.5, 14], 'Color', 'w');
t = tiledlayout(3, 1, 'TileSpacing', 'tight', 'Padding', 'compact');
x = linspace(0, 10, 500);
% Stacked Channel 1
ax1 = nexttile;
plot(ax1, x, sin(x), 'k-');
ylabel(ax1, 'Ch 1 (µV)');
ax1.XTickLabel = {}; % Hide redundant x-ticks
% Stacked Channel 2
ax2 = nexttile;
plot(ax2, x, sin(2*x), 'b-');
ylabel(ax2, 'Ch 2 (µV)');
ax2.XTickLabel = {}; % Hide redundant x-ticks
% Stacked Channel 3 (Bottom panel keeps x-tick labels)
ax3 = nexttile;
plot(ax3, x, sin(3*x), 'r-');
ylabel(ax3, 'Ch 3 (µV)');
xlabel(ax3, 'Time Elapsed (s)');
% Link x-axes across all three stacked subplots
linkaxes([ax1, ax2, ax3], 'x');
% Save publication-quality vector graphic
exportgraphics(t, 'multi_channel_figure.pdf', 'ContentType', 'vector');
When computational tasks require resolving underlying mathematical models before plotting, researchers can verify closed-form solutions using the MATLAB equation solver.
Output and how to read it
When you execute subplot or tiledlayout routines, MATLAB outputs an interactive figure window and, when scripted, an exported graphics file on disk:
- Figure Window Structure: The figure displays an ordered matrix of coordinate axes within a single container. Each subplot contains its own independent coordinate frame, tick marks, labels, and plot children. In legacy
subplot, axes are positioned using normalized figure coordinates ([left, bottom, width, height]), leaving default spacing gaps to avoid label collisions. Intiledlayout, the layout engine manages interior margins dynamically, contracting tile margins whenTileSpacingis set to'compact'or'tight'. - Linked Axis Inspection: When
linkaxesis active, interacting with any panel in the figure window (such as using the zoom or pan tools from the figure toolbar) immediately updates the coordinate limits of all synchronized partner axes in real time. - Export Verification: Using
exportgraphicscrops surrounding desktop canvas padding down to the outer bounding box of the layout. Authors should inspect exported PDF or PNG outputs at 100% zoom to verify:- Font sizes remain legible when scaled down to journal column dimensions (minimum 7–8 pt recommended).
- Tick labels on upper stacked subplots are cleanly suppressed without leaving blank vertical gaps.
- Shared global titles (
title(t, ...)) and super-titles (sgtitle(...)) do not truncate or collide with topmost plot boundaries.
Troubleshooting
Common failure modes and documented fixes for MATLAB subplot workflows:
- Overlapping panel labels in subplot: In legacy
subplot(m, n, p), titles and axis labels on adjacent plots often collide when tick labels are long or font sizes are large. Solution: Migrate totiledlayoutwith'TileSpacing', 'compact', or manually increase figure canvas height usingfig.Position. - Accidental deletion of existing plots: Calling
subplot(m, n, p)with inconsistent grid dimensions (for example, switching betweensubplot(2, 2, 1)andsubplot(3, 1, 2)inside the same script) causes MATLAB to delete any existing axes whose bounding box overlaps the newly defined position. Solution: Keep grid dimensions(m, n)identical across all calls within a figure, or usetiledlayout, which preserves tile hierarchies regardless of individual axes updates. - linkaxes error: Axes must belong to the same figure: Calling
linkaxeswith an invalid object or an axes handle from a closed figure throws an error. Solution: Ensure all handles passed intolinkaxespoint to valid 2D axes instantiated in the active figure window:linkaxes([ax1, ax2], 'x'). - Super-title overlaps the top row of subplots: Calling
sgtitlebefore configuring individual panel titles can cause MATLAB to miscalculate the upper figure margin. Solution: Callsgtitleas the final command after all subplots and titles have been drawn, or switch totiledlayoutand usetitle(t, ...). - Legends shift subplot axes sizes: Calling
legendinside a legacysubplotcompresses the plot box of that specific tile to make room for the legend box, leaving unequal subplot widths across columns. Solution: Usetiledlayoutand position the legend in an adjacent tile or outside the layout grid by settinglgd.Layout.Tile = 'east';.
Free alternatives (table)
For research groups operating in open-source computational environments or writing reproducible analysis pipelines without proprietary licenses, several open alternatives provide equivalent multi-panel plotting:
| Tool / Environment | Multi-Panel Syntax | Variable Spanning & Layouts | Shared Axis Linking | Export Options & License |
|---|---|---|---|---|
| GNU Octave | subplot(m, n, p) |
Compatible with MATLAB subplot(m, n, [p1 p2]) indexing |
Supports linkaxes(ax, 'x') across 2D plots |
PDF, EPS, PNG via print; GNU GPLv3 |
| Python (Matplotlib) | plt.subplots(nrows, ncols) or subplot_mosaic |
GridSpec and subplot_mosaic support arbitrary rectangular spans |
Native sharex=True and sharey=True parameters |
PDF, SVG, EPS, PNG via savefig; BSD-compatible (PSF) |
| R (patchwork / ggplot2) | p1 + p2 / p3 or facet_wrap() |
Arbitrary mathematical layout composition ((p1 | p2) / p3) |
Automatic scale sharing across facets (scales = "free_y") |
PDF, SVG, TIFF, PNG via ggsave; GNU GPL |
| Julia (Plots.jl) | plot(p1, p2, layout=(m, n)) |
Macro-based @layout [a b; c{0.7h}] for custom proportions |
link = :both or link = :x across subplot layouts |
PDF, SVG, PNG via savefig; MIT License |
FAQ
How do I create a subplot in MATLAB?
Call subplot(m, n, p), where m is the total number of rows, n is the total number of columns, and p is the index of the specific tile you want to activate (numbered from 1 starting at top-left and proceeding row by row). Any subsequent plotting command will draw into that active subplot.
What is the difference between subplot and tiledlayout in MATLAB?
subplot(m, n, p) is MATLAB’s legacy layout function, which places individual axes at rigid, pre-calculated positions with fixed margins. Introduced in R2019b, tiledlayout(m, n) is the modern layout manager that controls spacing (TileSpacing, Padding) across the entire grid, supports multi-tile spanning (nexttile([rows, cols])), and allows global figure titles and shared axis labels.
How do I share an X or Y axis across multiple MATLAB subplots?
Store the handles of the axes you want to synchronize (for example, ax1 = nexttile; and ax2 = nexttile;) and pass them to the linkaxes function along with the target dimension: linkaxes([ax1, ax2], 'x') to lock the horizontal scale, or linkaxes([ax1, ax2], 'y') to lock the vertical scale.
How do I add a main title over all subplots in MATLAB?
In traditional subplot grids, use sgtitle('Your Super Title') to center a title across all subplots in the figure. In modern tiledlayout grids, pass the layout object directly to the title function: title(t, 'Your Overall Title').
How do I make a MATLAB subplot span multiple rows or columns?
In legacy subplot, specify an array of linear indices: subplot(2, 2, [1 2]) spans the first two columns across row 1. In modern tiledlayout, pass a span vector to nexttile: nexttile([1, 2]) creates a tile that spans 1 row and 2 columns.
How do I adjust spacing between subplots in MATLAB to make them tight?
When using tiledlayout, configure the spacing properties directly upon initialization or by setting properties on the layout object: t.TileSpacing = 'tight'; and t.Padding = 'compact';. This eliminates excessive white margins between subplots without manual position calculations.
Sources (official docs)
Checked 2026-11-07.
- MathWorks Documentation, subplot: Create axes in tiled positions
- MathWorks Documentation, tiledlayout: Create tiled chart layout
- MathWorks Documentation, nexttile: Navigate to tile in tiled chart layout
- MathWorks Documentation, linkaxes: Synchronize limits of specified 2-D axes
- MathWorks Documentation, sgtitle: Add title to grid of subplots
- MathWorks Documentation, exportgraphics: Save plot or graphics object to file







