How to create a subplot in MATLAB

Subplots in MATLAB enable the simultaneous display of multiple plots within a single figure. Using the subplot() function, MATLAB divides the figure into a grid of rows and columns. Each cell in this grid represents a subplot, with its position indicating its location within the grid. By specifying the row and column indexes, subplot() activates a specific subplot for plotting. This efficient arrangement simplifies the creation of multipanel visualizations, facilitating comparisons and insights across different datasets or perspectives.

Syntax

The syntax of the subplot() function is as follows:

subplot(m, n, p)

In the syntax,

  • m specifies the total number of rows in the subplot grid.

  • n specifies the total number of columns in the subplot grid.

  • p specifies the position of the subplot to activate for plotting.

The number of total positions depends on the size of the matrix. A 2×32 \times 3 matrix has a total of 66 positions, from 1 to 6. 1 is upper left corner and 6 is lower right corner.

Implementation

Let’s review the following example on how to create subplots using the code.

% Create some sample data
x = 0:0.1:10;
sin_data = sin(x);
cos_data = cos(x);
tan_data = tan(x);
% Create a figure window
a = figure();
% Create subplot 1
subplot(3,1,1); % Divide the figure into 3 rows, 1 column, and select the first subplot
plot(x, sin_data);
title('Sin(x)');
% Create subplot 2
subplot(3,1,2); % Select the second subplot
plot(x, cos_data);
title('Cos(x)');
% Create subplot 3
subplot(3,1,3); % Select the third subplot
plot(x, tan_data);
title('Tan(x)');

Explanation

  • Line 2: It creates a vector x containing values ranging from 00 to 1010 with a step size of 0.10.1.

  • Lines 3–5: These calculate the sine, cosine, and tangent values of each element in the x vector and stores the result in the sin_data, cos_data, and tan_data variable respectively.

  • Line 8: It creates a new figure window and assigns its handle to the variable a.

  • Lines 11–12: These divide the figure into a grid of33rows and11column and selects the first subplot for subsequent plotting commands. The first subplot is for Sin(x). It then plots the sin_data against the x on the currently selected subplot.

  • Line 13: It adds a title Sin(x) to the current subplot.

  • Lines 16–17: These select the second subplot for subsequent plotting commands. The second subplot is for Cos(x). It then plots the cos_data against the x on the currently selected subplot.

  • Line 18: It adds a title Cos(x) to the current subplot.

  • Lines 21–22: These select the third subplot for subsequent plotting commands. The third subplot is for Tan(x). It then plots the tan_data against the x on the currently selected subplot.

  • Line 23: It adds a title Tan(x) to the current subplot.

Copyright ©2024 Educative, Inc. All rights reserved