Accelerating the pace of engineering and science

# Documentation Center

• Trial Software

## Specify Legend Descriptions During Line Creation

This example shows how to plot data and specify its associated legend description during the plotting command.

Plot three sine curves. For each line, set the DisplayName property to a descriptive string.

x = linspace(0,2*pi,100);
y1 = sin(x);
y2 = sin(x) + pi/2;
y3 = sin(x) + pi;

figure
hold all

hLine(1) = plot(x,y1,'DisplayName','sin(x)');
hLine(2) = plot(x,y2,'DisplayName','sin(x) + \pi/2');
hLine(3) = plot(x,y3,'DisplayName','sin(x) + \pi');

hold off % reset hold state to off


The graph does not display the legend until you call the legend function. Display the legend for the three lines by passing their handles to the legend function.

legend(hLine)


If you do not pass strings to legend, then legend uses the DisplayName properties as descriptions for each line. If the DisplayName property does not have a value, then legend uses a default string of the form 'data1', 'data2', and so on.