In this example we are going to plot multiple lines onto a single axis. Additionally, we choose a different appearance for the lines and create a legend.
% create sample data
x = linspace(-2,2,100); % 100 linearly spaced points from -2 to 2
y1 = x.^2;
y2 = 2*x.^2;
y3 = 4*x.^2;
% create plot
figure; % open new figure
plot(x,y1, x,y2,'--', x,y3,'-.'); % plot lines
grid minor; % add minor grid
title('Quadratic functions with different curvatures');
xlabel('x');
ylabel('f(x)');
legend('f(x) = x^2', 'f(x) = 2x^2', 'f(x) = 4x^2', 'Location','North');
In the above example, we plotted the lines with a single plot
-command. An alternative is to use separate commands for each line. We need to hold the contents of a figure with hold on
the latest before we add the second line. Otherwise the previously plotted lines will disappear from the figure. To create the same plot as above, we can use these following commands:
figure; hold on;
plot(x,y1);
plot(x,y2,'--');
plot(x,y3,'-.');
The resulting figure looks like this in both cases: