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);
p1 = plot(x,y1,'DisplayName','sin(x)');
hold on

y2 = sin(x) + pi/2;
p2 = plot(x,y2,'DisplayName','sin(x) + \pi/2');

y3 = sin(x) + pi;
p3 = plot(x,y3,'DisplayName','sin(x) + \pi');
hold off

The graph does not display the legend until you call the legend function. Display the legend for the three lines.

legend([p1 p2 p3])

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

See Also

| |

Was this topic helpful?