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 axes

Syntax

  • lgd = legend(___)
    example
  • [lgd,icons,plots,txt] = legend(___)
  • legend(visibilityOption)
  • legend('off')
    example

Description

example

legend('show') creates a legend that includes items for all charts in the current axes. For the labels, the legend uses the text from the DisplayName properties of the charts. If the DisplayName property is empty, then the legend uses a label of the form 'dataN'. If there are no charts in the axes, then this command creates an empty legend. If a legend exists, then this command ensures that it is visible.

example

legend(label1,...,labelN) sets the legend labels. Specify the labels as a list of character vectors, such as legend('Jan','Feb','Mar').

legend(labels) sets the labels using a cell array of character vectors or a character matrix; for example, legend({'Jan','Feb','Mar'}).

example

legend(labels,Name,Value) sets legend properties using one or more name-value pair arguments. You must specify the labels using a cell array; for example, legend({'A','B'},'FontSize',12).

example

legend(obj,___) only includes items in the legend for the graphics objects listed in obj. Specify the graphics objects before specifying the labels.

example

legend(ax,___) uses the axes specified by ax instead of the current axes. Specify the axes as the first input argument.

example

legend(___,'Location',lcn) sets the legend location. For example, 'Location','northeast' creates the legend in the upper right corner of the axes. You can use this option after any of the input argument combinations in the previous syntax group.

example

legend(___,'Orientation',ornt), where ornt is 'horizontal', displays the legend items side-by-side. The default for ornt is 'vertical', which stacks the items vertically.

example

legend(boxOption), where boxOption is 'off', removes the legend background and outline. The default for boxOption is 'on', which displays the legend background and outline.

example

lgd = legend(___) returns the legend object. Use lgd to query and set properties of the legend after it is created. For a list of properties, see Legend Properties.

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

    Note:   This syntax is not recommended. It creates a legend that does not support all graphics features. Instead, use the lgd = legend(__) syntax to return the legend object and set Legend Properties.

legend(visibilityOption) controls the visibility of the legend, where visibilityOption is 'hide' or 'toggle'.

example

legend('off') deletes the legend.

Examples

collapse all

Plot two lines and add a legend to the current axes. Specify the legend labels as input arguments to the legend function.

x = -pi:pi/20:pi;
y1 = sin(x);
plot(x,y1)

hold on
y2 = cos(x);
plot(x,y2,'--')
hold off

legend('sin(x)','cos(x)')

Plot two lines. Specify the legend labels during the plotting commands by setting the DisplayName property to the desired text. Then, add a legend.

x = linspace(-3,3,25);
y1 = sin(x);
plot(x,y1,'DisplayName','sin(x)')

hold on
y2 = cos(x);
plot(x,y2,'--','DisplayName','cos(x)')

legend('show')

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')

Plot three lines and return the chart line objects created. Then, create a legend that includes only two of the lines by specifying the first input argument as a vector of the chart line objects to include.

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

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

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

legend([p1 p3],'First','Third')

Plot two lines and add a legend. Control the location of the legend by setting the Location property. Control the orientation by setting the Orientation property.

x = -pi:pi/20:pi;
y1 = sin(x);
plot(x,y1)

hold on
y2 = cos(x);
plot(x,y2,'--')
hold off

legend('sin(x)','cos(x)','Location','northwest','Orientation','horizontal')

Plot two lines and create a legend. Then, add a title to the legend.

x = -pi:pi/20:pi;
y1 = sin(x);
plot(x,y1)

hold on
y2 = cos(x);
plot(x,y2)
hold off

lgd = legend('sin(x)','cos(x)');
title(lgd,'My Legend Title')

Plot a line chart and a stem chart. Add a legend to the axes and set properties of the legend using name-value pair arguments. When you specify name-value pair arguments, you must specify the labels using a cell array.

x = linspace(-3,3,25);
y1 = sin(x);
plot(x,y1)

hold on
y2 = cos(x);
stem(x,y2)
hold off

legend({'sin(x)','cos(x)'},'FontSize',12,'TextColor','blue')

Plot a line chart and a stem chart. Add a legend to the axes and assign the legend object to the variable lgd. Then, use lgd to modify properties of the legend after it is created.

x = linspace(-3,3,25);
y1 = sin(x);
plot(x,y1,'DisplayName','sin(x)')

hold on
y2 = cos(x);
stem(x,y2,'DisplayName','cos(x)')
hold off

lgd = legend('show');
lgd.FontSize = 12;
lgd.TextColor = 'blue';

Create a stem chart and a line chart. Add a legend to the lower left corner of the axes. Then, remove the legend background and outline.

x = linspace(0,2*pi,50);
y1 = sin(x);
stem(x,y1,'DisplayName','sin(x)')

hold on
y2 = cos(x);
plot(x,y2,'DisplayName','cos(x)')
hold off

legend('Location','southwest')
legend('boxoff')

Create a chart with a legend. Then, delete the legend.

plot(rand(3))
legend('line 1','line 2','line 3')

legend('off')

Related Examples

Input Arguments

collapse all

Label for each graphics object, specified as separate arguments of character vectors. To include special characters or Greek letters in the labels, use TeX markup. For a table of options, see the Interpreter property. To specify labels that are keywords, such as 'Location' or 'off', use a cell array of character vectors or a character array.

Example: legend('Sin Function','Cos Function')

Example: legend('\gamma','\sigma')

Label for each graphics object, specified as a cell array of character vectors or a character array. To include special characters or Greek letters in the labels, use TeX markup. For a table of options, see the Interpreter property.

Example: legend({'Sin Function','Cos Function'})

Example: legend(['Sin Function';'Cos Function'])

Example: legend({'\gamma','\sigma'})

Graphics object to include in the legend, specified as a vector.

Target axes, specified as an axes object or a polar axes object. If you do not specify the axes, then the legend function uses the current axes.

Legend 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 occurs with plot data
'bestoutside'To the right of the axes
'none'Determined by Position property. Use the Position property to display the legend in a custom location.

Example: legend('Location','northeastoutside')

Orientation, specified as one of these values:

  • 'vertical' — Stack the legend items vertically.

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

Example: legend('Orientation','horizontal')

Display of legend background, specified as one of these values:

  • 'boxon' — Display the legend background and outline.

  • 'boxoff' — Do not display the legend background and outline

Example: legend('boxoff')

Legend visibility, specified as one of these values:

  • 'hide' — Hide the legend.

  • 'toggle' — Toggle the legend visibility.

Example: legend('toggle')

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: legend({'A','B'},'FontSize',12,'TextColor','blue') creates a legend with blue, 12-point font.

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

collapse all

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 0.5]

Example: 'blue'

Font size, specified as a scalar value greater than zero in point units. 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.

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/.

Output Arguments

collapse all

Legend object. Use lgd to view or modify properties of the legend after it is created.

plot(rand(3))
lgd = legend('line1','line2','line3');
lgd.FontSize = 12;
lgd.FontWeight = 'bold';

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

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

    Note:   This output argument is not recommended.

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

    Note:   This output argument is not recommended.

Text used for legend labels, returned as a cell array of character vectors.

    Note:   This output argument is not recommended. Instead, access the labels using the String property of the legend.

More About

collapse all

Tips

  • Axes can have only one legend. If a legend exists, then the legend function updates the existing legend. Recalling the legend function does not reset legend properties, such as the location or orientation. The [lgd,icons,plots,txt] = legend(__) syntax is an exception; if a legend exists, then this command deletes the legend and creates a new one.

  • The legend reflects the visibility of graphics objects in the axes. Graphics objects that have a Visible property set to 'off' appear as grayed out items in the legend.

  • To label more than 20 objects in the legend, 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?