legend

Adds a legend that names the data series of the axes.

Category: Graphics > Formatting and Annotation

Syntax

legend(label1, ..., labelN)

Labels the plotted series in order with the given text.

legend(labels)

Takes the labels from a cell array or string array.

legend

Creates a legend using each series' DisplayName, or data1, data2 and so on.

legend(___, 'Location', loc)

Places the legend, for example 'southwest' or 'northeastoutside'.

legend off

Removes the legend. legend boxoff hides only its frame.

lgd = legend(___)

Returns the legend object.

Description

The legend lists one entry per series in the axes, showing a sample of its line or marker next to the label. With explicit labels, they are matched to the series in drawing order; with the DisplayName property set when plotting, legend with no arguments uses those names and stays correct if the order changes.

Call legend after the series exist, because a legend is not updated by series added later unless it is requested again.

Input arguments

label1, ..., labelN
Text labels, one per series, in the order the series were drawn.
Location
Position of the legend. The default is 'northeast'.

Output arguments

lgd
Legend object, class matlab.graphics.illustration.Legend, with properties such as String and Location.

Example

Names from DisplayName

x = 0:0.2:6;
plot(x, sin(x), 'DisplayName', 'sin')
hold on
plot(x, cos(x), 'DisplayName', 'cos')
hold off
lgd = legend;
lgd.String
Output
ans = 1×2 cell

    {'sin'}    {'cos'}

See also

plot title xlabel hold colorbar