Experiment 7: Multiple Plots in One Figure in MATLAB. Multiple Plots
Experiment 7: Multiple Plots in One Figure in MATLAB. Multiple Plots
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.
Create a vector x of 401 equally spaced points on [0, 1].
Add a grid.
Legends
When there are multiple plots in the same figure it is a good idea to add a legend, using, for
example,
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
If you have already created a plot and later wish to add another plot, then the hold command is
useful.
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.
Here is a 2 by 2 grid of subplots to make it clear how the numbering of subplots works.
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.
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 equal
help axis
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.
Add a grid.
MATLAB draws a plot in the current figure window. Figure windows are labelled 1, 2, 3, ... The
command
figure
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.