Documentation

This is machine translation

Translated by Microsoft
Mouse over text to see original. Click the button below to return to the English verison of the page.

legend

Add legend to graph

Syntax

  • legend(label1,...,labelN)
    example
  • legend(label1,...,labelN,'Location',Value)
    example
  • legend(___,'Orientation',Value)
    example
  • legend(labels)
  • legend(labels,Name,Value)
    example
  • legend('show')
  • legend('hide')
  • legend('toggle')
  • legend('off')
    example
  • legend('boxon')
  • legend('boxoff')
    example
  • l = legend(___)
  • [l,icons,plots,txt] = legend(___)

Description

example

legend(label1,...,labelN) creates a legend for the current axes using the specified labels. The legend shows an icon of the associated object next to each label. Specify the labels as a comma-separated list of character vectors, for example, legend('Jan','Feb','Mar').

example

legend(label1,...,labelN,'Location',Value) specifies the legend location. Set Value to a location option such as 'northoutside'. For a list of options, see the Location property.

example

legend(___,'Orientation',Value) specifies the legend orientation. This option can be used after either of the input argument combinations in the previous syntaxes. Set Value to either 'vertical' or 'horizontal'. For more information, see the Orientation property.

legend(labels) creates a legend for the current axes using the specified labels. Specify labels as either a cell array or a matrix, for example, legend({'Jan','Feb','Mar'}).

example

legend(labels,Name,Value) specifies legend properties. For example, 'FontSize',12 sets the font size to 12 points. For a list of properties, see Legend Properties.

example

legend(obj,___) specifies the charts to include in the legend. Specify obj as a vector of graphics objects. This option can precede any of the input argument combinations in the previous syntaxes.

legend('show') makes the legend in the current axes visible. If a legend does not exist, then MATLAB® creates one and sets the labels using the DisplayName properties of the charts. If a chart does not have a DisplayName property value, then the label is of the form 'data1', 'data2', and so on.

legend('hide') hides the legend associated with the current axes. Hiding the legend does not delete it.

legend('toggle') toggles the legend visibility. If a legend does not exist, then MATLAB creates one.

example

legend('off') deletes the legend from the current axes.

legend('boxon') displays the box around the legend.

example

legend('boxoff') removes the box around the legend.

example

legend(ax,___) uses the axes specified by ax instead of the current axes (gca). The option, ax, can precede any of the previous input argument combinations.

l = legend(___) returns the legend object. Use l to query and set properties of the legend after it is created.

    Note:   Starting in R2014b, the legend function returns a legend object. In previous releases it returns an axes object.

[l,icons,plots,txt] = legend(___) additionally returns the objects used to create the legend icons, the objects plotted in the graph, and an array of labels.

    Note:   This syntax is not recommended and creates a legend that does not support all graphics features. Use the l = legend(__) syntax to return the legend object and set Legend Properties instead.

Examples

collapse all

Add Legend to Chart

Plot two lines and add a legend to the chart.

x = -pi:pi/20:pi;
y1 = sin(x);
y2 = cos(x);
plot(x,y1,'-ro',x,y2,'-.b')
legend('sin(x)','cos(x)')

Specify Legend Location

Plot two lines. Add a legend to the top left corner of the axes by specifying the 'Location' property as 'northwest'.

x = -pi:pi/20:pi;
y1 = sin(x);
y2 = cos(x);
plot(x,y1,'-ro',x,y2,'-.b')
legend('sin(x)','cos(x)','Location','northwest')

Specify Legend Orientation

Plot two lines and add a horizontal legend above the axes.

x = -pi:pi/20:pi;
y1 = sin(x);
y2 = cos(x);
plot(x,y1,'-ro',x,y2,'-.b')
legend('sin(x)','cos(x)','Location','northoutside','Orientation','horizontal')

Add Title to Legend

Create a chart with a legend. Then, add a title to the legend.

x = -pi:pi/20:pi;
y1 = sin(x);
y2 = cos(x);
plot(x,y1,x,y2)
l = legend('sin(x)','cos(x)');
title(l,'My Legend Title')

Change Legend Font Size

Create the data, x, ydata, and ycos. Plot ydata and ycos. Add a legend that has small, bold font. To specify Name,Value pairs when creating a legend, specify the labels using a cell array.

x = linspace(0,4*pi,100);
ydata = cos(x) + 0.5*randn(1,100);
ycos = cos(x);
plot(x,ydata,'*',x,ycos)
legend({'Collected Data','y = cos(x)'},'FontSize',8,'FontWeight','bold')

Display Subset of Lines in Legend

Plot five lines and return the chart line objects from the plot function.

x = linspace(0,3*pi);
y1 = sin(x);
p1 = plot(x,y1);

y2 = sin(x - pi/4);
hold on
p2 = plot(x,y2);

y3 = sin(x - pi/2);
p3 = plot(x,y3);

y4 = sin(x - 3*pi/4);
p4 = plot(x,y4);

y5 = sin(x - pi);
p5 = plot(x,y5);
hold off

Add a legend for the first and last lines, p1 and p5.

legend([p1,p5],'sin(x)','sin(x-\pi)')

Remove Legend Border

Combine a stem chart and a line chart. Add a legend to the bottom left corner of the axes and remove the legend border.

x = linspace(0,2*pi,50);
ysin = sin(x);
stem(x,ysin)
hold on
ycos = cos(x);
plot(x,ycos)
hold off

legend('sin(x)','cos(x)','Location','southwest')
legend('boxoff')

Specify Custom Legend Size and Location

Combine two scatter plots. Use axis equal to set equal scaling along both the x-axis and y-axis. Add a legend to the center of the axes by specifying the Position property. To set the Position property when creating a legend, define the legend labels as a cell array by using curly braces, {}.

theta = linspace(0,2*pi,100);
x1 = sin(theta);
y1 = cos(theta);
scatter(x1,y1)

x2 = 2*sin(theta);
y2 = 2*cos(theta);
hold on
scatter(x2,y2,'*g')
hold off
axis equal

legend({'radius = 1','radius = 2'},'Position',[0.39,0.45,0.25,0.1])

Delete Legend

Create a plot of sine and cosine and add a legend.

x = linspace(0,2*pi,50);
ysin = sin(x);
ycos = cos(x);
plot(x,ysin,x,ycos)
legend('sine','cosine')

Delete the legend.

legend('off')

Specify Axes for Legend

Create a figure with two subplots and return the two axes objects, ax1 and ax2. Plot random data in each subplot. Add a legend to the upper subplot by specifying ax1 as the first input argument to legend.

y1 = rand(3);
ax1 = subplot(2,1,1);
plot(y1)

y2 = rand(5);
ax2 = subplot(2,1,2);
plot(y2)

legend(ax1,'Line 1','Line 2','Line 3')

Related Examples

Input Arguments

collapse all

label1,...,labelN — Label for each objectcomma-separated list of character vectors

Label for each object, specified as a comma-separated list of character vectors.

Example: legend('Sine Function','Cosine Function')

The legend associates the labels with objects in the same order that the objects are listed in the axes Children property. MATLAB sets the String property of the legend to the specified labels. MATLAB also sets the DisplayName properties of the objects to the specified labels.

If you do not specify the labels, then legend uses the DisplayName properties of the objects instead. If an object does not have a DisplayName property, or if you have not defined a value for this property, then legend uses a label of the form 'data1', 'data2', and so on.

To use keywords, such as 'Location' or 'off' as legend labels, use the labels input argument instead.

labels — Description for each objectcell array of character vectors | matrix of character vectors

Description for each object, specified as a cell array or matrix of character vectors.

Example: legend({'Sine Function','Cosine Function'})

If labels is a matrix, then the legend function uses each row of the matrix to label a set of data. The legend associates the labels with objects in the same order that the objects are listed in the axes Children property.

MATLAB sets the String property of the legend to the specified labels. MATLAB also sets the DisplayName properties of the objects to the specified labels.

If you do not specify the labels, then legend uses the DisplayName properties of the objects instead. If an object does not have a DisplayName property, or if you have not defined a value for this property, then legend uses a label of the form 'data1', 'data2', and so on.

obj — List of graphics objects to include in legendvector

List of graphics objects to include in the legend, specified as a vector. Specifying objects is useful if you do not want to add a description for every object in the graph.

These are the graphics objects that can be included in the legend:

  • Animated line objects

  • Area objects

  • Bar series objects

  • Chart line objects

  • Chart surface objects

  • Contour objects

  • Errorbar series objects

  • Group objects

  • Histogram objects

  • Patch objects

  • Primitive line objects

  • Primitive surface objects

  • Quiver series objects

  • Scatter series objects

  • Stair objects

  • Stem series objects

  • Transform objects

ax — Axes objectaxes object

Axes object. If you do not specify an axes object, then the legend function adds a legend for the current axes.

Name-Value Pair Arguments

Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and Value is the corresponding value. Name must appear inside single quotes (' '). You can specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.

Example: 'FontSize',12,'TextColor','blue'

The properties listed here are only a subset. For a complete list see Legend Properties.

'Location' — Location with respect to axes'north' | 'south' | 'east' | 'west' | 'northeast' | ...

Location with respect to the axes, specified as one of the location values listed in this table.

ValueDescription
'north'Inside top of axes
'south'Inside bottom of axes
'east'Inside right of axes
'west'Inside left of axes
'northeast'Inside top-right of axes (default for 2-D axes)
'northwest'Inside top-left of axes
'southeast'Inside bottom-right of axes
'southwest'Inside bottom-left of axes
'northoutside'Above the axes
'southoutside'Below the axes
'eastoutside'To the right of the axes
'westoutside'To the left of the axes
'northeastoutside'Outside top-right corner of the axes (default for 3-D axes)
'northwestoutside'Outside top-left corner of the axes
'southeastoutside'Outside bottom-right corner of the axes
'southwestoutside'Outside bottom-left corner of the axes
'best'Inside axes where least conflict with data in plot
'bestoutside'To the right of the axes
'none'Determined by Position property

To display the legend in a location that is not listed in the table, use the Position property to specify a custom location. If you set the Position property, then MATLAB automatically sets the Location property to 'none'.

'Orientation' — Orientation'vertical' (default) | 'horizontal'

Orientation, specified as one of these values:

  • 'vertical' — Stacks the legend items vertically. This is the default.

  • 'horizontal' — Lists the legend items side-by-side.

Example: 'horizontal'

'Box' — Box outline'on' (default) | 'off'

Box outline, specified as one of these values:

  • 'on' — Displays the box around the legend. This is the default.

  • 'off' — Removes the box around the legend.

Example: 'off'

'String' — Legend labelscell array

Legend labels, specified as a cell array. If you specify the labels either by setting the String property or as input to the legend function, then MATLAB uses the specified labels. If you do not specify labels, then MATLAB uses the DisplayName properties of the objects, or labels of the form 'data1', 'data2', and so on. The String property updates to reflect the labels used.

Example: {'Sine','Cosine','Tangent'}

'Interpreter' — Interpretation of text characters'tex' (default) | 'latex' | 'none'

Interpretation of text characters, specified as one of these values:

  • 'tex' — Interpret characters using a subset of TeX markup.

  • 'latex' — Interpret characters using LaTeX markup.

  • 'none' — Display literal characters.

TeX Markup

By default, MATLAB supports a subset of TeX markup. Use TeX markup to add superscripts and subscripts, modify the font type and color, and include special characters in the text.

This table lists the supported modifiers with the Interpreter property set to 'tex'. Modifiers remain in effect until the end of the text. Superscripts and subscripts are an exception because they only modify the next character or the characters within the curly braces.

ModifierDescriptionExample
^{ }Superscript'text^{superscript}'
_{ }Subscript'text_{subscript}'
\bfBold font'\bf text'
\itItalic font'\it text'
\slOblique font (usually the same as italic font)'\sl text'
\rmNormal font'\rm text'
\fontname{specifier}Font name — Set specifier as the name of a font family. You can use this in combination with other modifiers.'\fontname{Courier} text'
\fontsize{specifier}Font size — Set specifier as a numeric scalar value in point units to change the font size.'\fontsize{15} text'
\color{specifier}Font color — Set specifer as one of these colors: red, green, yellow, magenta, blue, black, white, gray, darkGreen, orange, or lightBlue.'\color{magenta} text'
\color[rgb]{specifier}Custom font color — Set specifier as a three-element RGB triplet.'\color[rgb]{0,0.5,0.5} text'

This table lists the supported special characters with the Interpreter property set to 'tex'.

Character SequenceSymbolCharacter SequenceSymbolCharacter SequenceSymbol

\alpha

α

\upsilon

υ

\sim

~

\angle

\phi

Φ

\leq

\ast

*

\chi

χ

\infty

\beta

β

\psi

ψ

\clubsuit

\gamma

γ

\omega

ω

\diamondsuit

\delta

δ

\Gamma

Γ

\heartsuit

\epsilon

ɛ

\Delta

Δ

\spadesuit

\zeta

ζ

\Theta

Θ

\leftrightarrow

\eta

η

\Lambda

Λ

\leftarrow

\theta

Θ

\Xi

Ξ

\Leftarrow

\vartheta

ϑ

\Pi

Π

\uparrow

\iota

ι

\Sigma

Σ

\rightarrow

\kappa

κ

\Upsilon

ϒ

\Rightarrow

\lambda

λ

\Phi

Φ

\downarrow

\mu

µ

\Psi

Ψ

\circ

º

\nu

ν

\Omega

Ω

\pm

±

\xi

ξ

\forall

\geq

\pi

π

\exists

\propto

\rho

ρ

\ni

\partial

\sigma

σ

\cong

\bullet

\varsigma

ς

\approx

\div

÷

\tau

τ

\Re

\neq

\equiv

\oplus

\aleph

\Im

\cup

\wp

\otimes

\subseteq

\oslash

\cap

\in

\supseteq

\supset

\lceil

\subset

\int

\cdot

·

\o

ο

\rfloor

\neg

¬

\nabla

\lfloor

\times

x

\ldots

...

\perp

\surd

\prime

´

\wedge

\varpi

ϖ

\0

\rceil

\rangle

\mid

|

\vee

\langle

\copyright

©

LaTeX Markup

To use LaTeX markup, set the Interpreter property to 'latex'. Use dollar symbols around the text, for example, use '$\int_1^{20} x^2 dx$' for inline mode or '$$\int_1^{20} x^2 dx$$' for display mode.

The displayed text uses the default LaTeX font style. The FontName, FontWeight, and FontAngle properties do not have an effect. To change the font style, use LaTeX markup.

The maximum size of the text that you can use with the LaTeX interpreter is 1200 characters. For multiline text, this reduces by about 10 characters per line.

For more information about the LaTeX system, see The LaTeX Project website at http://www.latex-project.org/.

'TextColor' — Text color[0,0,0] (default) | RGB triplet | character vector

Text color, specified as an RGB triplet or a character vector of a color name. The default color is black with an RGB triplet value of [0,0,0].

An RGB triplet is a three-element row vector whose elements specify the intensities of the red, green, and blue components of the color. The intensities must be in the range [0,1], for example, [0.4 0.6 0.7]. This table lists the long and short color name options and the equivalent RGB triplet values.

Long NameShort NameRGB Triplet
'yellow''y'[1 1 0]
'magenta''m'[1 0 1]
'cyan''c'[0 1 1]
'red''r'[1 0 0]
'green''g'[0 1 0]
'blue''b'[0 0 1]
'white''w'[1 1 1]
'black''k'[0 0 0]

Example: [0,0,1]

Example: 'blue'

'FontSize' — Font size9 (default) | scalar value greater than zero

Font size, specified as a scalar value greater than zero in point units. The default value is 9 points. If you change the axes font size, then MATLAB automatically sets the legend font size to 90% of the axes font size. If you manually set the legend font size, then changing the axes font size does not affect the legend.

Example: 12

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical

Output Arguments

collapse all

l — Legend objectlegend object

Legend object. Use l to modify the legend after it has been created.

icons — Objects used to create legend icons and labelstext, patch, and line objects

Objects used to create the legend icons and labels, returned as text, patch, and line objects.

plots — Objects plotted in axesvector of objects

Objects plotted in the axes, returned as a vector of objects.

txt — Legend labelscell array

Legend labels, returned as a cell array.

More About

collapse all

Tips

  • Axes can have only one legend.

  • To label more than 20 objects in the legend, you must specify a label for each object. Otherwise, legend depicts only the first 20 objects in the graph.

See Also

Functions

Properties

Introduced before R2006a

Was this topic helpful?