legend - Add legend to axes - MATLAB (original) (raw)

Main Content

Syntax

Description

legend creates a legend with descriptive labels for each plotted data series. For the labels, the legend uses the text from theDisplayName properties of the data series. If theDisplayName property is empty, then the legend uses a label of the form 'dataN'. The legend automatically updates when you add or delete data series from the axes. This command creates a legend in the current axes, which is returned by the gca command. If the current axes is empty, then the legend is empty. If no axes exist, thenlegend creates a Cartesian axes.

example

legend([label1,...,labelN](#bt6ef%5Fq-1-label1labelN)) sets the legend labels. Specify the labels as a list of character vectors or strings, such as legend('Jan','Feb','Mar').

example

legend([labels](#bt6ef%5Fq-1-labels)) sets the labels using a cell array of character vectors, a string array, or a character matrix, such as legend({'Jan','Feb','Mar'}).

legend([subset](#bt6ef%5Fq-1-subset),___) only includes items in the legend for the data series listed insubset. Specify subset as a vector of graphics objects. You can specify subset before specifying the labels or with no other input arguments.

example

legend([target](#bt6ef%5Fq-1-target),___) uses the axes or standalone visualization specified by target instead of the current axes. Specify the target as the first input argument.

example

legend(___,'Location',[lcn](#bt6ef%5Fq-1-lcn)) sets the legend location. For example, 'Location','northeast' positions the legend in the upper right corner of the axes. Specify the location after other input arguments.

example

legend(___,'Orientation',[ornt](#bt6ef%5Fq-1-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(___,[Name,Value](#namevaluepairarguments)) sets legend properties using one or more name-value pair arguments.

example

legend([bkgd](#bt6ef%5Fq-1-boxOption)), wherebkgd is 'boxoff', removes the legend background and outline. The default for bkgd is'boxon', which displays the legend background and outline.

example

[lgd](#bt6ef%5Fq-1-lgd) = legend(___) returns the Legend object. Uselgd to query and set properties of the legend after it is created. For a list of properties, see Legend Properties.

legend([vsbl](#bt6ef%5Fq-1-visibilityOption)) controls the visibility of the legend, where vsbl is 'hide','show', or 'toggle'.

legend('off') deletes the legend.

Examples

collapse all

Add Legend to Current Axes

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

x = linspace(0,pi); y1 = cos(x); plot(x,y1)

hold on y2 = cos(2*x); plot(x,y2)

legend('cos(x)','cos(2x)')

Figure contains an axes object. The axes object contains 2 objects of type line. These objects represent cos(x), cos(2x).

If you add or delete a data series from the axes, the legend updates accordingly. Control the label for the new data series by setting the DisplayName property as a name-value pair during creation. If you do not specify a label, then the legend uses a label of the form 'dataN'.

Note: If you do not want the legend to automatically update when data series are added to or removed from the axes, then set the AutoUpdate property of the legend to 'off'.

y3 = cos(3*x); plot(x,y3,'DisplayName','cos(3x)') hold off

Figure contains an axes object. The axes object contains 3 objects of type line. These objects represent cos(x), cos(2x), cos(3x).

Delete the legend.

Figure contains an axes object. The axes object contains 3 objects of type line. These objects represent cos(x), cos(2x), cos(3x).

Add Legend to Specific Axes

You can display a tiling of plots using the tiledlayout and nexttile functions. Call the tiledlayout function to create a 2-by-1 tiled chart layout. Call the nexttile function to create the axes objects ax1 and ax2. Plot random data in each axes. Add a legend to the upper plot by specifying ax1 as the first input argument to legend.

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

y2 = rand(5); ax2 = nexttile; plot(y2)

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

Figure contains 2 axes objects. Axes object 1 contains 3 objects of type line. These objects represent Line 1, Line 2, Line 3. Axes object 2 contains 5 objects of type line.

Specify Legend Labels During Plotting Commands

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(0,pi); y1 = cos(x); plot(x,y1,'DisplayName','cos(x)')

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

legend

Figure contains an axes object. The axes object contains 2 objects of type line. These objects represent cos(x), cos(2x).

Exclude Line from Legend

To exclude a line from the legend, specify its label as an empty character vector or string. For example, plot two sine waves, and add a dashed zero line by calling the yline function. Then create a legend, and exclude the zero line by specifying its label as ''.

x = 0:0.2:10; plot(x,sin(x),x,sin(x+1)); hold on yline(0,'--') legend('sin(x)','sin(x+1)','')

Figure contains an axes object. The axes object contains 3 objects of type line, constantline. These objects represent sin(x), sin(x+1).

List Entries in Columns and Specify Legend Location

Plot four lines. Create a legend in the northwest area of the axes. Specify the number of legend columns using the NumColumns property.

x = linspace(0,pi); y1 = cos(x); plot(x,y1)

hold on y2 = cos(2*x); plot(x,y2)

y3 = cos(3*x); plot(x,y3)

y4 = cos(4*x); plot(x,y4) hold off

legend({'cos(x)','cos(2x)','cos(3x)','cos(4x)'},... 'Location','northwest','NumColumns',2)

Figure contains an axes object. The axes object contains 4 objects of type line. These objects represent cos(x), cos(2x), cos(3x), cos(4x).

By default, the legend orders the items from top to bottom along each column. To order the items from left to right along each row instead, set the Orientation property to 'horizontal'.

Reverse Order of Legend Items

Since R2023b

You can reverse the order of the legend items by setting the Direction property of the legend. For example, plot four lines and add a legend.

plot([4 5 6 7; 0 1 2 3]) lgd = legend("First","Second","Third","Fourth");

Figure contains an axes object. The axes object contains 4 objects of type line. These objects represent First, Second, Third, Fourth.

Reverse the order of the legend items.

lgd.Direction = "reverse";

Figure contains an axes object. The axes object contains 4 objects of type line. These objects represent First, Second, Third, Fourth.

Display Shared Legend in Tiled Chart Layout

When you want to share a legend between two or more plots, you can display the legend in a separate tile of the layout. You can place the legend within the grid of tiles, or in an outer tile.

Create three plots in a tiled chart layout.

t = tiledlayout('flow','TileSpacing','compact'); nexttile plot(rand(5)) nexttile plot(rand(5)) nexttile plot(rand(5))

Figure contains 3 axes objects. Axes object 1 contains 5 objects of type line. Axes object 2 contains 5 objects of type line. Axes object 3 contains 5 objects of type line.

Add a shared legend, and move it to the fourth tile.

lgd = legend; lgd.Layout.Tile = 4;

Figure contains 3 axes objects. Axes object 1 contains 5 objects of type line. Axes object 2 contains 5 objects of type line. Axes object 3 contains 5 objects of type line.

Next, add a fourth plot and move the legend to the east tile.

nexttile plot(rand(5)) lgd.Layout.Tile = 'east';

Figure contains 4 axes objects. Axes object 1 contains 5 objects of type line. Axes object 2 contains 5 objects of type line. Axes object 3 contains 5 objects of type line. Axes object 4 contains 5 objects of type line.

Included Subset of Graphics Objects in Legend

If you do not want to include all of the plotted graphics objects in the legend, then you can specify the graphics objects that you want to include.

Plot three lines and return the Line objects created. Create a legend that includes only two of the lines. Specify the first input argument as a vector of the Line objects to include.

x = linspace(0,pi); y1 = cos(x); p1 = plot(x,y1);

hold on y2 = cos(2*x); p2 = plot(x,y2);

y3 = cos(3*x); p3 = plot(x,y3); hold off

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

Figure contains an axes object. The axes object contains 3 objects of type line. These objects represent First, Third.

Create Legend with LaTeX Markup

Create a plot, and add a legend with LaTeX markup by calling the legend function and setting the Interpreter property to 'latex'. Surround the markup with dollar signs ($).

x = 0:0.1:10; y = sin(x); dy = cos(x); plot(x,y,x,dy); legend('$sin(x)$','$\frac{d}{dx}sin(x)$','Interpreter','latex');

Figure contains an axes object. The axes object contains 2 objects of type line. These objects represent <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>s</mi><mi>i</mi><mi>n</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">sin(x)</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">s</span><span class="mord mathnormal">in</span><span class="mopen">(</span><span class="mord mathnormal">x</span><span class="mclose">)</span></span></span></span>, <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mfrac><mi>d</mi><mrow><mi>d</mi><mi>x</mi></mrow></mfrac><mi>s</mi><mi>i</mi><mi>n</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\frac{d}{dx}sin(x)</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1.2251em;vertical-align:-0.345em;"></span><span class="mord"><span class="mopen nulldelimiter"></span><span class="mfrac"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.8801em;"><span style="top:-2.655em;"><span class="pstrut" style="height:3em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">d</span><span class="mord mathnormal mtight">x</span></span></span></span><span style="top:-3.23em;"><span class="pstrut" style="height:3em;"></span><span class="frac-line" style="border-bottom-width:0.04em;"></span></span><span style="top:-3.394em;"><span class="pstrut" style="height:3em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">d</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.345em;"><span></span></span></span></span></span><span class="mclose nulldelimiter"></span></span><span class="mord mathnormal">s</span><span class="mord mathnormal">in</span><span class="mopen">(</span><span class="mord mathnormal">x</span><span class="mclose">)</span></span></span></span>.

Add Title to Legend

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

x = linspace(0,pi); y1 = cos(x); plot(x,y1)

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

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

Figure contains an axes object. The axes object contains 2 objects of type line. These objects represent cos(x), cos(2x).

Remove Legend Background

Plot two lines and create a legend in the lower left corner of the axes. Then, remove the legend background and outline.

x = linspace(0,pi); y1 = cos(x); plot(x,y1)

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

legend({'cos(x)','cos(2x)'},'Location','southwest') legend('boxoff')

Figure contains an axes object. The axes object contains 2 objects of type line. These objects represent cos(x), cos(2x).

Specify Legend Font Size and Color

You can change different aspects of a legend by setting properties. You can set properties by specifying name-value arguments when you call legend, or you can set properties of the Legend object after you call legend.

Plot four lines of random data. Create a legend and assign the Legend object to the variable lgd. Set the FontSize and TextColor properties using name-value arguments.

rdm = rand(4); plot(rdm)

lgd = legend({'Line 1','Line 2','Line 3','Line 4'},... 'FontSize',12,'TextColor','blue');

Figure contains an axes object. The axes object contains 4 objects of type line. These objects represent Line 1, Line 2, Line 3, Line 4.

Modify the legend after it is created by referring to lgd. Set the NumColumns property using the object dot property name notation.

Figure contains an axes object. The axes object contains 4 objects of type line. These objects represent Line 1, Line 2, Line 3, Line 4.

Specify Width of Legend Icons

Since R2024b

You can specify the widths of the legend icons by setting the IconColumnWidth property. For example, plot a line and two sets of scattered data.

% Create the data x = 1:50; sample1 = x + randn(1,50); sample2 = (x-5) + randn(1,50); y = x - 10;

% Plot the data plot(x,y) hold on scatter(x,sample1,"filled") scatter(x,sample2,"filled") hold off

Figure contains an axes object. The axes object contains 3 objects of type line, scatter.

Add a horizontal legend to the top of the plot. The line icon is wider than the two marker icons, so the legend contains some extra white around the marker icons.

lgd = legend("Expected","Sample 1","Sample 2"); lgd.Location = "north"; lgd.Orientation = "horizontal";

Figure contains an axes object. The axes object contains 3 objects of type line, scatter. These objects represent Expected, Sample 1, Sample 2.

Decrease the width of the icon column by setting the IconColumnWidth property to 10. As a result, the line icon is shorteneted and the space around the markers is reduced.

lgd.IconColumnWidth = 10;

Figure contains an axes object. The axes object contains 3 objects of type line, scatter. These objects represent Expected, Sample 1, Sample 2.

Input Arguments

collapse all

label1,...,labelN — Labels (as separate arguments)

character vectors | strings

Labels, specified as a comma-separated list of character vectors or strings.

To exclude an item from the legend, specify the corresponding label as an empty character vector or string.

To include special characters or Greek letters in the labels, use TeX or LaTeX 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, a string array, or a character array.

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

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

Example: legend("Sample A","","Sample C")

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

labels — Labels (as an array)

cell array of character vectors | string array | categorical array

Labels, specified as a cell array of character vectors, string array, or categorical array.

To exclude an item from the legend, specify the corresponding label as an empty character vector in the cell array, or as an empty string in the string array.

To include special characters or Greek letters in the labels, use TeX or LaTeX markup. For a table of options, see the Interpreter property.

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

Example: legend(["Sin Function","Cos Function"])

Example: legend({'Sample A','','Sample C'})

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

Example: legend(categorical({'Alabama','New York'}))

subset — Data series to include in legend

vector of graphics objects

Data series to include in the legend, specified as a vector of graphics objects.

target — Target for legend

Axes object | PolarAxes object | GeographicAxes object | standalone visualization

Target for legend, specified as an Axes object, aPolarAxes object, a GeographicAxes object, or a standalone visualization with aLegendVisible property, such as aGeographicBubbleChart object. If you do not specify the target, then the legend function uses the object returned by the gca command as the target.

Standalone visualizations do not support modifying the legend appearance, such as the location, or returning the Legend object as an output argument..

lcn — Legend location

'north' | 'south' | 'east' | 'west' | 'northeast' | ...

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

Value Description
'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 the plot data at the time that you create the legend. If the plot data changes, you might need to reset the location to 'best'.
'bestoutside' Outside top-right corner of the axes (when the legend has a vertical orientation) or below the axes (when the legend has a horizontal orientation)
'layout' A tile in a tiled chart layout. To move the legend to a different tile, set the Layout property of the legend.
'none' Determined by Position property. Use the Position property to display the legend in a custom location.

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

ornt — Orientation

'vertical' (default) | 'horizontal'

Orientation, specified as one of these values:

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

bkgd — Legend box display

'boxon' (default) | 'boxoff'

Legend box display, specified as one of these values:

Example: legend('boxoff')

vsbl — Legend visibility

'hide' | 'show' | 'toggle'

Legend visibility, specified as one of these values:

Example: legend('hide')

Name-Value Arguments

Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

Example: legend({'A','B'},'TextColor','blue','FontSize',12) creates a legend with blue, 12-point font.

Note

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

TextColor — Text color

[0 0 0] (default) | RGB triplet | hexadecimal color code | 'r' | 'g' | 'b' | ...

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

For a custom color, specify an RGB triplet or a hexadecimal color code.

Alternatively, you can specify some common colors by name. This table lists the named color options, the equivalent RGB triplets, and hexadecimal color codes.

Color Name Short Name RGB Triplet Hexadecimal Color Code Appearance
"red" "r" [1 0 0] "#FF0000" Sample of the color red
"green" "g" [0 1 0] "#00FF00" Sample of the color green
"blue" "b" [0 0 1] "#0000FF" Sample of the color blue
"cyan" "c" [0 1 1] "#00FFFF" Sample of the color cyan
"magenta" "m" [1 0 1] "#FF00FF" Sample of the color magenta
"yellow" "y" [1 1 0] "#FFFF00" Sample of the color yellow
"black" "k" [0 0 0] "#000000" Sample of the color black
"white" "w" [1 1 1] "#FFFFFF" Sample of the color white
"none" Not applicable Not applicable Not applicable No color

Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB® uses in many types of plots.

RGB Triplet Hexadecimal Color Code Appearance
[0 0.4470 0.7410] "#0072BD" Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue
[0.8500 0.3250 0.0980] "#D95319" Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange
[0.9290 0.6940 0.1250] "#EDB120" Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow
[0.4940 0.1840 0.5560] "#7E2F8E" Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple
[0.4660 0.6740 0.1880] "#77AC30" Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green
[0.3010 0.7450 0.9330] "#4DBEEE" Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue
[0.6350 0.0780 0.1840] "#A2142F" Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

Example: [0 0 1]

Example: 'blue'

Example: '#0000FF'

Font size, specified as a scalar value greater than zero in point units. The default font size depends on the specific operating system and locale.

If you change the axes font size, then MATLAB automatically sets the font size of the colorbar to 90% of the axes font size. If you manually set the font size of the colorbar, then changing the axes font size does not affect the colorbar font.

NumColumns — Number of columns

1 (default) | positive integer

Number of columns, specified as a positive integer. If there are not enough legend items to fill the specified number of columns, then the number of columns that appear might be fewer.

Use the Orientation property to control whether the legend items appear in order along each column or along each row.

Example: lgd.NumColumns = 3

Output Arguments

collapse all

lgdLegend object

Legend object

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

Tips

Algorithms

Version History

Introduced before R2006a

expand all

R2024b: Support for multiple outputs will be removed

Calling the legend function with multiple output arguments returns a warning that the syntax will be removed in a future release.

[lgd,icons,plots,txt] = legend(...)

This syntax creates a legend that does not support some functionality. For example, you cannot add a title to the legend or specify the number of legend columns. Also, the legend does not automatically update when you add or remove data series from the axes.

Instead, return the Legend object and setLegend Properties.

R2023b: Legend order is reversed for stacked bar charts and area charts

The default order of legend items for stacked (vertical) bar charts and area charts is now reversed to match the stacking order of the chart. Previously, the legend items were listed in the opposite order of stacked bars and area charts.

To preserve the order of previous releases, set the Direction property of the legend to "normal".

Comparison of default legends for a stacked bar chart in R2023a and R2023b. The order of legend items in R2023b matches the stacking order of the bars.

R2022b: Legends update when you delete lines or other plot objects

If you delete an object from the axes, such as a line or scatter object, the legend updates to reflect the change regardless of whether theAutoUpdate property is set to "on" or"off".

Previously, the legend did not update when you removed objects from the axes while the AutoUpdate property was set to"off".

R2021a: Passing an empty label to the legend function omits the entry from the legend

When you call the legend function and specify a label as an empty character vector, an empty string, or an empty element in a cell array or string array, the corresponding entry is omitted from the legend. In R2020b and earlier releases, the entry appears in the legend without a label.

For example, this code plots two sine waves and a reference line aty=0. Then it creates a legend with three labels, where the last label is empty. In R2020b, the third line appears in the legend without a label. In R2021a, the third line is omitted from the legend.

x = 0:0.2:10; plot(x,sin(x),x,sin(x+1)); hold on yline(0,'--') legend('sin(x)','sin(x+1)','')

Comparison of empty legend labels in R2020b and R2021a.

To keep an entry in the legend without a label, include a space character in the label. For example, to update the preceding code, specify the last label as a character vector containing a space (' ').

legend('sin(x)','sin(x+1)',' ')

Alternatively, if you do not want to display a space character, you can pass the individual line objects to the legend function with an array of labels. To get the individual line objects, call each plotting function with an output argument.

x = 0:0.2:10; p = plot(x,sin(x),x,sin(x+1)); hold on line0 = yline(0,'--'); legend([p(1) p(2) line0], {'sin(x)','sin(x+1)',''});

R2018b: legend interprets arguments as property names when property exists

Starting in R2018b, if you pass an argument to the legend function that matches the name of a legend property, the function interprets the argument as the name of a name-value pair. In previous releases, thelegend function recognized name-value pairs only when the first argument was a cell array.

As a result of this change, in most cases, it is unnecessary to specify the first argument as a cell array when using name-value pairs. However, if you want a label in your legend that matches the name of a legend property, such asPosition or NumColumns, then you_must_ specify all the labels in a cell array. Otherwise, thelegend function interprets the argument as a name-value pair instead of a label.

Description Recommended Code
If you want a label in your legend that matches the name of a legend property, such as'NumColumns', then specify all the labels in a cell array. If you specify'NumColumns' outside of a cell array, the legend function interprets it as a name-value pair. legend({'Label1','NumColumns','Label3','Label4'},'NumColumns',2)
If none of your labels match the name of a legend property, then you do not need to use a cell array around the labels. legend('Label1','Label2','Label2')

R2017b: legend creates axes if they do not exist

Starting in R2017b, if axes do not exist, then the legend function creates them.

R2017a: Legends automatically update when you add or remove data

Starting in R2017a, the legend automatically updates when you add or remove data series from the axes. If you do not want the legend to automatically update, set theAutoUpdate property of the legend to'off'.

lgd = legend; lgd.AutoUpdate = 'off';

Returning multiple outputs using this syntax is no longer recommended.

[lgd,icons,plots,txt] = legend(...)