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,
mspecifies the total number of rows in the subplot grid.nspecifies the total number of columns in the subplot grid.pspecifies 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.
Implementation
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)');
Explanation
Line 2: It creates a vector
xcontaining values ranging fromto with a step size of . Lines 3–5: These calculate the sine, cosine, and tangent values of each element in the
xvector and stores the result in thesin_data,cos_data, andtan_datavariable 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 of
rows and column and selects the first subplot for subsequent plotting commands. The first subplot is for Sin(x). It then plots thesin_dataagainst thexon 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 thecos_dataagainst thexon 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 thetan_dataagainst thexon the currently selected subplot.Line 23: It adds a title
Tan(x)to the current subplot.
Free Resources