13.2. Multiple plots on the same axes#
Everytime the plot()
function is called MATLAB creates a new axes in the figure window. To plot more than one plot on the same axes we use the hold on
keyword to prevent MATLAB from creating a new axes and the hold off
keyword when we have finished adding the plots.
To include multiple plots on the same axis simply add another plot()
function.
hold on
plot(x1, y1) % first plot
plot(x2, y2) % second plot
hold off
For example, lets plot the functions \(y = x^2\), \(y = x^3\) and \(y = x^4\) on the same axes. Enter the following code into your program.
% Multiple plots on the same axes
x = linspace(-2, 2, 100);
y1 = x .^ 2;
y2 = x .^ 3;
y3 = x .^ 4;
clf
hold on
plot(x, y1)
plot(x, y2)
plot(x, y3)
hold off
xlabel('$x$', FontSize=16, Interpreter='latex')
ylabel('$y$', FontSize=16, Interpreter='latex')
Run your program and you should see the following plot added to the plot window.
Note that MATLAB uses a different colour for each subsequent plot if the plot colour has not been specified.
Note
In the example above we used the clf
command to clear the current figure window. This was because we had already set axis limits and aspect ratio for our previous plots which would have been used for our new plot. Like clear
for clearing variables, it is good practice to use clf
whenever you are creating a new plot.
13.2.1. Legends#
The problem with our plot of the multiple functions above is that someone viewing the plot has no way of known which line represents which function. To provide this information we can add a legend to our plot using the legend()
function
legend([plot1 label, plot2 label, ...], fontspec)
Where plotx label
are the labels of each of the plots in the order they were added to the axes, fontspec
are optional commands that specify the font properties and 'location'
is the location specified using 'north'
, 'east'
, 'south'
, 'west'
, 'northeast'
, 'southeast'
, 'southwest'
or 'northwest'
.
Lets add a legend to our plot, enter the following code into your program.
% Legend
legend('$y = x^2$', '$y = x^3$', '$y = x^4$', FontSize=14, Interpreter='latex', Location='southeast')
Run your program and you should see the following plot added to the plot window.
13.2.2. Exercises#
Produce plots of the functions \(y=\sin(x)\) and \(y=\cos(x)\) over the domain \(x\in[-2\pi, 2\pi]\) on the same set of axes. Use a red line for the plot of \(y = \sin(x)\) and a dashed blue line for the plot of \(y = \cos(x)\), scale the \(y\)-axis so that it uses the range \([-2,2]\) and insert a legend in the top-left hand corner of the plot.
The \((x, y)\) co-ordinates of points on a circle centred at \((c_x,c_y)\) with radius \(r\) can be calculated using \(x = c_x + r \cos(\theta)\) and \(y = c_y + r\sin(\theta)\) for \(\theta\in [0,2\pi]\). Plot four circles centred at \((5, 5)\) with radii \(r=1,2,3,4\). Adjust the aspect ratio to display so that the circles look circular and not like ellipses.