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.
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 1
to 6
. 1
is upper left corner and 6
is lower right corner.
Let’s review the following example on how to create subplots using the code.
% Create some sample datax = 0:0.1:10;sin_data = sin(x);cos_data = cos(x);tan_data = tan(x);% Create a figure windowa = figure();% Create subplot 1subplot(3,1,1); % Divide the figure into 3 rows, 1 column, and select the first subplotplot(x, sin_data);title('Sin(x)');% Create subplot 2subplot(3,1,2); % Select the second subplotplot(x, cos_data);title('Cos(x)');% Create subplot 3subplot(3,1,3); % Select the third subplotplot(x, tan_data);title('Tan(x)');
Line 2: It creates a vector x
containing values ranging from
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 ofSin(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.
Free Resources