# legend

Add legend to graph

## Syntax

• legend(s1,...,sN)
example
• legend(s1,...,sN,'Location',Value)
example
• legend(___,'Orientation',Value)
example
• legend(str)
• legend(str,Name,Value)
example
• legend(entries,___)
example
• legend('boxon')
• legend('boxoff')
example
• legend('hide')
• legend('show')
• legend('toggle')
• legend('off')
example
• legend(ax,___)
example
• h = legend(___)
• [h,icons,plots,s] = legend(___)

## Description

example

legend(s1,...,sN) creates a legend in the current axes using the specified strings to label each set of data. The legend shows an icon of the associated object next to each string.

example

legend(s1,...,sN,'Location',Value) specifies the legend location. Set Value to a location string such as 'northoutside'. For a list of strings, see the Location property.

example

legend(___,'Orientation',Value) specifies the legend orientation. This option can be used with either of the input argument combinations in the previous syntaxes. Set Value as either 'vertical' or 'horizontal'. For more information, see the Orientation property. 
legend(str) creates a legend in the current axes and uses the entries in str to label each set of data. Specify str as either a cell array of strings or a matrix of strings.

example

legend(str,Name,Value) specifies legend properties. Use this syntax if you want to specify Name,Value pairs other than Location and Orientation when creating a legend. For example, 'FontSize',12 sets the font size to 12 points.

example

legend(entries,___) displays legend entries for the objects in the graph specified by the vector entries. Use this syntax if you want to display legend entries for only some of the objects in the graph. The option, entries, can precede any of the input argument combinations in the previous syntaxes. 
legend('boxon') displays the box around the legend.

example

legend('boxoff') removes the box around the legend.
legend('hide') hides the legend associated with the current axes. Hiding the legend does not delete it.
legend('show') makes the legend in the current axes visible. If a legend does not exist, then MATLAB® creates one using the default strings.
legend('toggle') toggles the legend visibility. If a legend does not exist, then MATLAB creates one using the default strings.

example

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

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.
h = legend(___) returns the legend object. Use h 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.
[h,icons,plots,s] = legend(___) additionally returns the objects used to create the legend icons, the objects plotted in the graph, and an array of text strings.

## Examples

collapse all

### Add Legend to Graph

Create a graph of sine and cosine. Add a legend to the graph indicating the two functions.

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

### Specify Legend Location

Create a graph of sine and cosine. Add a legend to the top left corner of the graph by specifying the 'Location' property as 'northwest'.

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

### Add Horizontal Legend Above Graph

Create a graph of sine and cosine. Add a horizontal legend above the axes.

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

### Change Legend Font Size

Define the data, x, ydata, and ycos.

rng default % initialize random number generator x = linspace(0,4*pi,100); ydata = cos(x) + 0.5*randn(1,100); ycos = cos(x); 

Plot ydata and ycos. Add a legend to the graph using a small, bold font. To specify Name,Value pairs when creating a legend, you must specify the legend description strings as a cell array by using curly braces, {}.

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

### Specify Legend Location and Remove Border

Create a plot of sine and cosine. Add a legend to the bottom left of the axes.

x = linspace(0,2*pi,50); ysin = sin(x); ycos = cos(x); figure stem(x,ysin) hold all plot(x,ycos) hold off legend('sin(x)','cos(x)','Location','southwest') 

Remove the legend border.

legend('boxoff') 

### Specify Custom Legend Size and Location

Define the data.

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

Create a scatter plot of two circles. Use axis equal to set equal scaling along both the x-axis and y-axis.

figure scatter(x1,y1) hold on scatter(x2,y2,'*g') hold off axis equal 

Add a legend to the center of the graph using the Position property. To set the Position property when creating a legend, you must define the legend strings as a cell array by using curly braces, {}.

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); figure 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 handles, ax1 and ax2. Plot random data in each subplot.

rng default % initialize random number generator y1 = rand(3); y2 = rand(5); figure ax1 = subplot(2,1,1); % upper subplot plot(y1) ax2 = subplot(2,1,2); % lower subplot plot(y2) 

Add a legend to the upper subplot by passing its axes handle to legend.

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

## Input Arguments

collapse all

### s1,...,sN — Description for each objectcomma-separated list of strings

Description for each object, specified as a comma-separated list of strings.

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

If you do not specify legend strings, 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 string of the form 'data1', 'data2', and so on.

Example: 'Sine Function','Cosine Function'

### str — Description for each objectcell array of strings | matrix of strings

Description for each object, specified as a cell array of strings or a matrix of strings. If str is a matrix, then the legend function uses each row of the matrix to label a set of data.

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

If you do not specify legend strings, 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 string of the form 'data1', 'data2', and so on.

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

### entries — 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:

### ax — Axes objectaxes object

Axes object. If you do not specify an axes, then the legend function adds a legend to 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 axessupported location string

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

Supported StringResulting Location
'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'.

Example: 'northoutside'

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

Orientation, specified as one of these values:

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

• 'horizontal' — Lists the legend entries 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 entry descriptionscell array of strings

Legend entry descriptions, specified as a cell array of strings. If you specify strings as input to legend, then MATLAB sets the String property to the specified strings and uses these strings in the legend display. If you do not specify strings, then MATLAB uses the DisplayName properties of the objects, or a string of the form 'data1', 'data2', and so on. The String property reflects the entries in the legend.

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 text strings using a subset of TeX markup.

• 'latex' — Interpret text strings 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 text type and color, and include special characters in the text string.

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

ModifierDescriptionExample of String
^{ }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'. 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 within the text string.

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

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

### 'TextColor' — Text color[0,0,0] or 'black' (default) | RGB triplet | supported color string

Text color, specified as an RGB triplet or a supported color string. 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 RGB triplet values that have equivalent color strings.

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

### h — Legend objectlegend object

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

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

Objects used to create the legend icons and descriptions, returned as text, patch, and line object.

### plots — Objects plotted in graphvector of objects

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

### s — Text strings used in legendcell array

Text strings used in the legend, returned as a cell array.

## More About

expand all

### Tips

• An axes can have only one legend.

• To use legend keywords, such as 'Location' or 'off' as legend descriptions, you must pass the string in a cell array to legend. For example, l = legend({'Location'}) displays a legend with the entry Location.

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

• legend associates strings with objects in the same order that the objects are listed in the axes Children property.

## See Also

### Properties

#### Introduced before R2006a

Was this topic helpful?

Get trial now