Syntax:
Basic Syntax:
legend(label1, ..., labelN)
legend(labels)
Subset Specification:
legend(subset, ___)
Target Specification:
legend(target, ___)
Position and Orientation:
legend(___, 'Location', lcn)
legend(___, 'Orientation', ornt)
Name-Value Pairs:
legend(___, Name, Value)
Background Customization:
legend(bkgd)
Output Variable:
lgd = legend(___)
Visibility Control:
legend(vsbl)
legend('off')
legend(label1,...,labelN)assigns specific labels to the legend items. Provide the labels as a list of character vectors or strings, such aslegend('Jan','Feb','Mar'). Alternatively, uselegend(labels)to set the labels using a cell array of character vectors, a string array, or a character matrix, such aslegend({'Jan','Feb','Mar'}).legend(subset,___)limits the legend to include only the items corresponding to the data series specified in thesubset. Specifysubsetas a vector of graphics objects. This can be used before specifying labels or without additional arguments.legend(target,___)designates a specific axes or standalone visualization as the target for the legend instead of the current axes. Thetargetis provided as the first input argument.legend(___,'Location',lcn)defines the location of the legend within the axes. For instance,legend(...,'Location','northeast')positions the legend in the upper-right corner.legend(___,'Orientation',ornt)adjusts the layout of the legend items. Whenorntis'horizontal', the items are displayed side-by-side. The default is'vertical', stacking the items vertically.legend(___,Name,Value)modifies legend properties using one or more name-value pair arguments.legend(bkgd), wherebkgdis'boxoff', removes the background and outline of the legend. The default value,'boxon', displays the background and outline.lgd = legend(___)returns the Legend object. This object can be used to query or set legend properties after creation. Refer to Legend Properties for a detailed list.legend(vsbl)manages the legend’s visibility, wherevsblcan be'hide','show', or'toggle'.legend('off')removes the legend from the axes.
Add Legend to Current Axes
Plot two lines and add a legend to the current axes by specifying the legend labels as arguments in 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)')

If you add or remove a data series from the axes, the legend automatically updates to reflect the changes. You can control the label for the new data series by specifying the DisplayName property as a name-value pair during its creation. If no label is specified, the legend assigns a default label in the format 'dataN'.
Note: To prevent the legend from automatically updating when data series are added or removed, set the AutoUpdate property of the legend to 'off'.
y3 = cos(3*x);
plot(x,y3,'DisplayName','cos(3x)')
hold off

Delete the legend.
legend('off')

Add Legend to Specific Axes
You can arrange multiple plots in a tiled layout using the tiledlayout and nexttile functions. First, use tiledlayout to create a 2-by-1 grid for the chart layout. Then, call nexttile to generate the axes objects ax1 and ax2. Plot random data in each of these axes. To add a legend to the top plot, specify ax1 as the first input argument when calling the legend function.
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'})

Specify Legend Labels During Plotting Commands
“Plot two lines and specify the legend labels by setting the DisplayName property to the desired text within the plotting commands. Afterward, add the legend to the plot.”
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

Exclude Line from Legend
To exclude a line from the legend, set its label to an empty character vector or string. For instance, plot two sine waves and add a dashed zero line using the yline function. Afterward, create a legend and exclude the zero line by assigning an empty label ('') to it.
x = 0:0.2:10;
plot(x,sin(x),x,sin(x+1));
hold on
yline(0,'--')
legend('sin(x)','sin(x+1)','')

List Entries in Columns and Specify Legend Location
Plot four lines and add a legend in the northwest corner of the axes. Use the ‘NumColumns’ property to specify the number of columns in the legend.
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)

By default, the legend arranges the items vertically, from top to bottom in each column. To change the layout and order the items horizontally, from left to right along each row, set the ‘Orientation’ property to ‘horizontal’.
Reverse Order of Legend Items
Starting from R2023b:
You can reverse the order of legend items by adjusting the Direction property of the legend. For instance, plot four lines and then add a legend to the plot.
plot([4 5 6 7; 0 1 2 3])
lgd = legend("First","Second","Third","Fourth");

“Reverse the sequence of the legend items.”
lgd.Direction = "reverse";

Display Shared Legend in Tiled Chart Layout
To share a legend between two or more plots, you can place the legend in a separate tile of the layout. It can either be positioned within the grid of tiles or in an outer tile.
First, 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))

Place a common legend and position it in the fourth tile.
lgd = legend;
lgd.Layout.Tile = 4;

Next, add a fourth plot and position the legend in the eastern tile.
nexttile
plot(rand(5))
lgd.Layout.Tile = 'east';

Included Subset of Graphics Objects in Legend
If you wish to exclude some of the plotted graphics objects from the legend, you can choose to specify only the ones you want to include.
For example, plot three lines and return the corresponding Line objects. Then, create a legend that includes only two of these lines by providing a vector of the specific Line objects you want to display in the legend.
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'})

Create Legend with LaTeX Markup
“To create a plot and add a legend with LaTeX markup, call the legend function and set the Interpreter property to ‘latex’. Enclose the markup with dollar signs ($) for proper formatting.”
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');

Add Title to Legend
“Plot two lines on the graph, create a legend to identify them, and 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')

Remove Legend Background
“Plot two lines and place the legend in the lower-left corner of the axes. Afterward, remove the legend’s 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')

Specify Legend Font Size and Color
You can modify various aspects of a legend by adjusting its properties. Properties can be set either by using name-value pairs when calling the legend function or by directly modifying the Legend object after creating it.
For example, to plot four lines of random data, create a legend, and assign the Legend object to a variable lgd, you can then modify 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');

“To modify the legend after it has been created, reference it using the lgd object. You can set the NumColumns property by using the dot notation with the object, like this:”
lgd.NumColumns = 2;

Specify Width of Legend Icons
“Starting from R2024b, you can adjust the width of the legend icons by setting the IconColumnWidth property. For instance, you can plot a line and two sets of scatter 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

“Add a horizontal legend at the top of the plot. The line icon is wider than the two marker icons, resulting in extra white space around the marker icons in the legend.”
lgd = legend("Expected","Sample 1","Sample 2");
lgd.Location = "north";
lgd.Orientation = "horizontal";

Reduce the width of the icon column by setting the IconColumnWidth property to 10. This will shorten the line icon and decrease the space around the markers.
lgd.IconColumnWidth = 10;

Input Arguments
label1,…,labelN — Labels (as separate arguments)
Labels are specified as a comma-separated list of character vectors or strings.
- To exclude an item from the legend, provide 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. Refer to the Interpreter property for a table of options.
- For labels that are keywords, such as 'Location' or 'off', use a cell array of character vectors, a string array, or a character array.
Examples:
1. legend('Sin Function', 'Cos Function')
2. legend("Sin Function", "Cos Function")
3. legend("Sample A", "", "Sample C")
4. legend('\gamma', '\sigma')
labels — Labels (as an array)
Labels are specified as a cell array of character vectors, a string array, or a categorical array.
- To exclude an item from the legend, provide the corresponding label as an empty character vector in the cell array or as an empty string in the string array.
- For including special characters or Greek letters in the labels, use TeX or LaTeX markup. Refer to the Interpreter property for a table of available options.
Examples:
1. legend({'Sin Function', 'Cos Function'})
2. legend(["Sin Function", "Cos Function"])
3. legend({'Sample A', '', 'Sample C'})
4. legend({'\gamma', '\sigma'})
5. legend(categorical({'Alabama', 'New York'}))
subset — Data series to include in legend
Data series to be included in the legend, specified as a vector of graphic objects.
target — Target for legend
The target for the legend can be specified as an Axes object, a PolarAxes object, a GeographicAxes object, or a standalone visualization with a LegendVisible property, such as a GeographicBubbleChart object. If no target is specified, the legend function uses the object returned by the gca command as the default target.
Note that standalone visualizations do not support modifying the legend’s appearance (e.g., location) or returning the Legend object as an output argument.
lcn — Legend location
Here is the table format for the legend location with respect to the axes:
| 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 of creation. Might need resetting if plot data changes. |
'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 the Position property. Use the Position property to display the legend in a custom location. |
Example: legend('Location','northeastoutside')
ornt — Orientation
Orientation can be specified as one of the following values:
'vertical'— Stacks the legend items vertically.'horizontal'— Displays the legend items side-by-side.
Example: legend('Orientation','horizontal')
bkgd — Legend box display
Legend box display can be specified as one of the following options:
'boxon'— Displays both the legend background and outline.'boxoff'— Hides both the legend background and outline.
Example:legend('boxoff')
vsbl — Legend visibility
Legend visibility can be set to one of the following values:
'hide'— Hides the legend.'show'— Displays the legend or creates one if it doesn’t exist.'toggle'— Switches the visibility of the legend.
Example: legend('hide')
