This example shows how to add a title, axis labels and a legend to a graph using the
legend functions. By default, these functions add the text to the current axes. The current axes is typically the last axes created or the last axes clicked with the mouse.
x as 100 linearly spaced values between
y2 as sine and cosine values of
x. Create a line plot of both sets of data.
x = linspace(-2*pi,2*pi,100); y1 = sin(x); y2 = cos(x); figure plot(x,y1,x,y2)
Add a title to the graph using the
title function. Pass the
title function a text string with the desired title.
To display Greek symbols in a title, use the TeX markup. Use the TeX markup,
\pi, to display the Greek symbol
title('Graph of Sine and Cosine Between -2\pi and 2\pi')
Add axis labels to the graph using the
ylabel functions. Pass these functions a text string with the desired label.
xlabel('-2\pi < x < 2\pi') % x-axis label ylabel('sine and cosine values') % y-axis label
Add a legend to the graph identifying each data set using the
legend function. Pass the
legend function a text string description for each line. Specify legend descriptions in the order that you plot the lines.
legend('y = sin(x)','y = cos(x)')
Change the location of the legend on the graph by setting its location using one of the eight cardinal or intercardinal directions. Display the legend at the bottom left corner of the axes by specifying its location as
To display the legend outside the axes, append
outside to any of the directions, for example,
legend('y = sin(x)','y = cos(x)','Location','southwest')