Add Title, Axis Labels, and Legend to Graph

This example shows how to add a title, axis labels and a legend to a graph using the title, xlabel, ylabel and 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.

Create Simple Line Plot

Define x as 100 linearly spaced values between $-2\pi$ and $2\pi$. Define y1 and 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);


Add Title

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 $\pi$.

title('Graph of Sine and Cosine Between -2\pi and 2\pi')

Add Axis Labels

Add axis labels to the graph using the xlabel and 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 Legend

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 Legend Location

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 'southwest'.

To display the legend outside the axes, append outside to any of the directions, for example, 'southwestoutside'.

legend('y = sin(x)','y = cos(x)','Location','southwest')

See Also

| | | |

Related Examples

Was this topic helpful?