by admin

2 Plots In One Figure Matlab

Plotting data is one of the most important tasks in Matlab programming. In this section, we will show you how to plot data, modify plots and save your work.

  1. 2 Plots In One Figure Matlab Tutorial
  2. 2 Plots In One Figure Matlab Probability
  3. 2 Plots In One Figure Matlab Matrix
  4. Matlab Multiple Plots One Figure

Basic Plot

Here is an example of a plot of a sine wave. Try to enter the following lines of code into your Matlab Command Window.

Example 1

The first two lines create the vectors that will be plotted. The third line creates the figure, saving the handle. The variable f is the figure handle, which can be used to reference the figure later. The fourth line plots the data, saving the plot handle. The variable h is the plot handle and can be used to reference and modify the plotted line. The next three lines all modify the axes, changing the labels and the title. This example can be used as a template for most basic 2-dimensional plotting tasks.

Features

Multiple Plots on One Axis

2 Plots In One Figure Matlab Tutorial

  1. These both figures have 4 plots in them (2×2 layout). I got them from two different Simulink models and want to make visual comparison of each plot. I've tried this code but it just merges one plot and other three plot spaces are left empty.
  2. Then call a plotting function to plot into the axes. For example, create two plots in a 2-by-1 layout. Add a title to each plot. Note: This code uses the tiledlayout function, which is available starting in R2019b. If you are using an earlier release, use the subplot function instead.
  3. These both figures have 4 plots in them (2×2 layout). I got them from two different Simulink models and want to make visual comparison of each plot. I've tried this code but it just merges one plot and other three plot spaces are left empty.

In this matlab simulink tutorial, how to plot multiple plots in same figure in Simulink without any knowledge of MATLAB programming.It is needed in compariso. The first two inputs tell MATLAB how to split the figure up. Imagine it as how many 'rows' and 'columns' of plots there will be in the figure. In the example above, our figure will have three rows of plots and one column. The third input to subplot tells MATLAB in what location to place the graph from the next plot command. This value will.

Plotting multiple sets of data on the same axes is a useful feature of Matlab. The hold command allows users to add multiple plots to the same axis.

Example 2

The hold on command can be used in place of hold all. However, if the hold on command is used, then the subsequent plots will be the default blue color with a solid line, unless another color and linestyle are specified. For this reason, the hold all command is better for most applications.

Multiple Axes on One Figure

There are times when putting multiple axes on the same figure helps to display results more clearly. The following command breaks the current figure up into m rows and n columns, and creates axes in the pth division.

In the following example, a set of axes will be created in the third division of the 2 x 2 area in the figure. Subplot counts the divisions first along rows from left to right, then along columns from up to down. This code will create a plot in the upper-right corner of the figure. Each set of axes has its own properties, labels, title and legend.

Example 3

Legend

The legend function in Matlab creates a legend in the current axes of the current figure. This function is useful for labeling multiple plots on the same axes.

Continuing from Example 2

This command will, by default, create a text box in the upper-right corner of the axes that shows both lines and their labels. Sometimes the default placement of the legend interferes with the data in the plot and another location is desirable.

This line of code will place the legend in the upper-left, or ‘NorthWest’, corner of the plot. The location of the legend can be set by using the ‘Location’ parameter. The location parameter can either be a 1×4 vector in the format of [left bottom width height], a string indicating a cardinal or intercardinal direction or a string telling Matlab to find the “best” location. The possible directions are ‘North’, ‘South’, ‘East’, ‘West’, ‘NorthEast’, ‘NorthWest’, ‘SouthEast’ and ‘SouthWest’. These directions are referenced to ‘North’ at the top-middle of the plot, just like a map.

Grid

The grid function allows a Matlab user to draw vertical and horizontal lines across the plot at intervals specified by the axis tick marks. The syntax for this command is quite simple.

Line Properties

Line properties can be modified in two different ways, using the plot command or using the set command. This section of the tutorial will use code that builds on Example 1.

Colors

This command will allow you to change the color of the plotted line.

Alternatively, the line color could have been set in the plot command.

Both of these commands will change the color of the line to red. Colors can be specified in three different ways: RGB Value, Short Name and Long Name.

Plot two functions in matlab

[table id=7 /]

Here is a table with all three specifications for eight different colors. Colors not in this table can be specified with an RGB Value. The RGB value must be a row vector of three elements, with each element in the range of [0,1].

Linestyle

Different linestyles are useful to change the appearance of your plot or to differentiate between different sets of data. The linestyle can be changed inside of a plot command or with the set command.

or

The following table shows the five different linestyles.

[table id=5 /]

Markers

2 Plots In One Figure Matlab

Markers can accomplish the same results as changing the plot’s linestyle. Markers can also be set with a plot or set command.

or

This table shows the fourteen different markers available in Matlab.

[table id=6 /]

Other Properties

Lines have many other parameters including ‘LineWidth’, ‘MarkerFaceColor’, ‘MarkerEdgeColor’ and ‘MarkerSize’. To see the rest of the properties that belong to a line, use the get command. To change any property, use the set command. Type the following command to see all the properties that you can change.

To get a single property, type this command.

Combining Multiple Property Commands

To set multiple properties at the same time, use a command with the following syntax.

For example, this line of code will create a green dotted line with upward-pointing triangles as markers.

However, the same properties can be changed in a plot command with a single string.

This is a common and useful Matlab shortcut and only works with the Color, Linestyle and Marker properties. Additionally, these three properties can be in any order within the string. Other properties can be set inside the plot command.

Try to experiment with the set, get and plot commands to change a variety line properties.

Axis Properties

The axes of a plot are a separate object in Matlab, and can be controlled by using set, get and other commands. The code in this section will continue using Example 2.

Axis Limits

This code will change the limits of the x-axis to [0,5] and the limits of the y-axis to [2,4]

Ticks

This code will change the locations of the tick marks on the axes. The parameter gca stands for “get current axes” and will return the handle of the axes of the current figure.

The x-axis should have 4 tick marks at intervals of pi from 0 to 3*pi. The y-axis should have 5 tick marks at intervals of 2 from 1 to 9. To check that this is true, see if you can set the limits of the axes back to their original values.

Tick Labels

Tick labels can be set by entering a cell array of strings that will become the tick labels. Each tick label should correspond to one tick.

This code should have set the tick labels on the x-axis to multiples of pi and tick labels on the y-axis to words that correspond to the tick locations.

Saving and Opening Figures

After creating and modifying a plot, saving the figure is often necessary. Matlab allows users to save figures and to load them later. The examples in this section will continue from Example 1.

Saving

2 Plots In One Figure Matlab Probability

Figures can be saved either as Matlab figures or as image files. Both of these commands save the figure from Example 1 as a Matlab figure.

or

These commands will save the figure in different formats.

The alternative format can also be used.

Opening

To open a figure, use the openfig command.

The variable g is the figure handle, which can be used reference the figure.

Summary

This tutorial shows how to create a basic two-dimensional plot and how to use some key features. There are many topics that this tutorial does not cover; however, any other questions can be answered by using a search engine or by going directly to the Mathworks website.

Multiple plots

The plot command can plot several sets of vectors.

Plot the functions y1 = sin(2 pi x) and y2 = cos(2 pi x) for x in the interval [0, 1] using 401 equally spaced points.

2 Plots In One Figure Matlab Matrix

Create a vector x of 401 equally spaced points on [0, 1].

Create a vector y1 of function values.

Create a vector y2 of function values.

Plot both sets points in the same figure.

Add a grid.

Add a title. What is still missing?

>> y1 = sin(2*pi*x);
>> plot(x, y1, x, y2)
>> title('sin(2 pi x) and cos(2 pi x)')

In general you can use

plot(x1, y1, s1, x2, y2, s2, x3, y3, s3)

where x1 and y1 are vectors of the same length and s1 is an optional string.

Legends

When there are multiple plots in the same figure it is a good idea to add a legend, using, for example,

legend(string1, string2, string3)

Here string1 is a string describing the first set of values plotted, string2 is a string describing the second set of values plotted, and string3 is a string describing the third set of values plotted.

You can use the mouse to reposition the legend box within the plot, or you can specify the location of the legend box. See

help legend

for more information.

The first string describes the first data set, the second string the second data set.

The hold command

If you have already created a plot and later wish to add another plot, then the hold command is useful.

Create the previous plot using two separate plot commands and the hold command.

Create the first plot assuming x, y1 and y2 are defined as above.

Turn the hold on.

Add the second plot.

Turn the hold off.

>> hold on
>> hold off

Note that when using a single plot command, MATLAB adjusts the colours for successive plots. When using the hold command you must explicitly set the colours, for example using plot(x, y2, 'g').

Subplots

Sometimes you want a single figure containing several individual subplots. The MATLAB command

subplot(m, n, k)

creates an m by n array of plots and positions you at plot number k, where the plots are numbered counting across rows.

The most common examples are

  • a 2 by 1 grid of subplots for two plots one on top of each other;
  • a 1 by 2 grid for two plots side by side.

Here is a 2 by 2 grid of subplots to make it clear how the numbering of subplots works.

Create plots of sin(k pi x) for x on [0, 1] and k = 1, 2, 3, 4 in one figure.

Create vector of plot points.

2 by 2 grid of subplots, at subplot 1.

Add plot on current subplot.

Add grid and title on current subplot.

2 by 2 grid of subplots, at subplot 2.

Add plot on current subplot.

Add grid and title on current subplot.

2 by 2 grid of subplots, at subplot 3.

Add plot on current subplot.

Add grid and title on current subplot.

2 by 2 grid of subplots, at subplot 4.

Add plot on current subplot.

Add grid and title on current subplot.

>> subplot(2,2,1)
>> grid on; title('k = 1')
>> plot(x, sin(2*pi*x))
>> subplot(2,2,3)
>> grid on; title('k = 3')
>> plot(x, sin(4*pi*x))

Axis limits

If you are really observant you will have noticed that the limits of the y-axis on the first subplot is from 0 to 1, while the other three plots all have y ranging from -1 to 1. MATLAB tries to choose good axis limits based on the data that is being plotted. However sometimes you want to change the axis limits.

The simplest way to do this is to use

xlim([xmin xmax])

to make the x-axis run from xmin to xmax. To adjust the limits of the y-axis use

ylim([ymin ymax])

to make the y-axis run from ymin to ymax. Note that the argument to xlim and ylim is a two element vector giving the lower and upper limits for the axis.

Another way to control the limits and scaling of the axes is to use the axis command, for example

axis([xmin xmax ymin ymax])

By default the x-scale is slightly larger than the y-scale, so you get a rectangular plot on the screen. To make the axis scaling equal use

axis equal

which is required to make a circle look like a circle!

As always, more information can be obtained by typing

help axis

in the MATLAB command window.

Plot the two circles (cos(t), sin(t)) and (cos(t), sin(t))/2 for t in [0, 2 pi]. Ensure the plot looks like circles not ellipses! Make both the x-axis and y-axis both go form -1.1 to 1.1.

Create vector t of parameter values.

Store the values of cos(t) and sin(t).

Plot the two curves.

Make the axis scaling equal.

Adjust the axis limits.

Add a grid.

>> ct = cos(t); st = sin(t);
>> axis equal
>> grid on

Figures

MATLAB draws a plot in the current figure window. Figure windows are labelled 1, 2, 3, ... The command

figure

creates a new figure window. Alternatively the command

figure(k)

where k is a positive integer, opens figure window k if it already exists, or creates figure window k if it does not exist.

Self-test Exercise

Plot the functions sin(x), x, and 2x/pi over the interval [0, pi/2], including the title 'Bounds on sin(x)', a grid, a legend and making sure the x-axis corresponds to the plot interval.

Answer:
x = linspace(0, pi/2, 401);
plot(x, sin(x), x, x, x, 2*x/pi);
title('Bounds on sin(x)')
grid on
legend('sin(x)', 'x', '2x/pi')
xlim([0, pi/2])
Use the mouse to select the text between the word 'Answer' and here to see the answer.

Summary

The plot command can plot several sets of data on the one set of axes. In this case a legend should be added.

Figure

Several different plots within the one figure can be created using the subplot command.

Matlab Multiple Plots One Figure

Axis limits and scaling can be modified with the xlim, ylim and axis commands.