Add legend to axes - MATLAB legend (2025)

Table of Contents
Syntax Description Examples Add Legend to Current Axes Add Legend to Specific Axes Specify Legend Labels During Plotting Commands Exclude Line from Legend List Entries in Columns and Specify Legend Location Reverse Order of Legend Items Display Shared Legend in Tiled Chart Layout Included Subset of Graphics Objects in Legend Create Legend with LaTeX Markup Add Title to Legend Remove Legend Background Specify Legend Font Size and Color Input Arguments label1,...,labelN — Labels (as separate arguments) character vectors | strings labels — Labels (as an array) cell array of character vectors | string array | categorical array subset — Data series to include in legend vector of graphics objects target — Target for legend Axes object | PolarAxes object | GeographicAxes object | standalone visualization lcn — Legend location 'north' | 'south' | 'east' | 'west' | 'northeast' | ... ornt — Orientation 'vertical' (default) | 'horizontal' bkgd — Legend box display 'boxon' (default) | 'boxoff' vsbl — Legend visibility 'hide' | 'show' | 'toggle' Name-Value Arguments NumColumns — Number of columns 1 (default) | positive integer Output Arguments lgd — Legend object Legend object Tips Algorithms Version History R2023b: Legend order is reversed for stacked bar charts and area charts R2022b: Legends update when you delete lines or other plot objects R2021a: Passing an empty label to the legend function omits the entry from the legend R2018b: legend interprets arguments as property names when property exists R2017b: legend creates axes if they do not exist R2017a: Legends automatically update when you add or remove data R2014b: Returning multiple outputs is not recommended See Also Functions Properties Topics MATLAB Command Americas Europe Asia Pacific FAQs

Add legend to axes

collapse all in page

Syntax

legend

legend(label1,...,labelN)

legend(labels)

legend(subset,___)

legend(target,___)

legend(___,'Location',lcn)

legend(___,'Orientation',ornt)

legend(___,Name,Value)

legend(bkgd)

lgd = legend(___)

legend(vsbl)

legend('off')

Description

example

legend creates a legend with descriptive labels for each plotted data series. For the labels, the legend uses the text from the DisplayName properties of the data series. If the DisplayName 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, then legend creates a Cartesian axes.

example

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

legend(labels) sets the labels using a cell array of character vectors, a string array, or a character matrix, such as legend({'Jan','Feb','Mar'}).

example

legend(subset,___) only includes items in the legend for the data series listed in subset. 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,___) 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) 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), 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) sets legend properties using one or more name-value pair arguments.

example

legend(bkgd), where bkgd is 'boxoff', removes the legend background and outline. The default for bkgd is 'boxon', which displays the legend background and outline.

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.

legend(vsbl) 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

Open Live Script

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

Add legend to axes - MATLAB legend (1)

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

Add legend to axes - MATLAB legend (2)

Delete the legend.

legend('off')

Add legend to axes - MATLAB legend (3)

Add Legend to Specific Axes

Open Live Script

Starting in R2019b, 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'})

Add legend to axes - MATLAB legend (4)

Specify Legend Labels During Plotting Commands

Open Live Script

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 offlegend

Add legend to axes - MATLAB legend (5)

Exclude Line from Legend

Open Live Script

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 onyline(0,'--')legend('sin(x)','sin(x+1)','')

Add legend to axes - MATLAB legend (6)

List Entries in Columns and Specify Legend Location

Open Live Script

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 ony2 = cos(2*x);plot(x,y2)y3 = cos(3*x);plot(x,y3)y4 = cos(4*x);plot(x,y4)hold offlegend({'cos(x)','cos(2x)','cos(3x)','cos(4x)'},... 'Location','northwest','NumColumns',2)

Add legend to axes - MATLAB legend (7)

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

Open Live Script

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");

Add legend to axes - MATLAB legend (8)

Reverse the order of the legend items.

lgd.Direction = "reverse";

Add legend to axes - MATLAB legend (9)

Display Shared Legend in Tiled Chart Layout

Open Live Script

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');nexttileplot(rand(5))nexttileplot(rand(5))nexttileplot(rand(5))

Add legend to axes - MATLAB legend (10)

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

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

Add legend to axes - MATLAB legend (11)

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

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

Add legend to axes - MATLAB legend (12)

Included Subset of Graphics Objects in Legend

Open Live Script

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 ony2 = cos(2*x);p2 = plot(x,y2);y3 = cos(3*x);p3 = plot(x,y3);hold offlegend([p1 p3],{'First','Third'})

Add legend to axes - MATLAB legend (13)

Create Legend with LaTeX Markup

Open Live Script

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

Add legend to axes - MATLAB legend (14)

Add Title to Legend

Open Live Script

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 ony2 = cos(2*x);plot(x,y2)hold offlgd = legend('cos(x)','cos(2x)');title(lgd,'My Legend Title')

Add legend to axes - MATLAB legend (15)

Remove Legend Background

Open Live Script

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 ony2 = cos(2*x);plot(x,y2)hold offlegend({'cos(x)','cos(2x)'},'Location','southwest')legend('boxoff')

Add legend to axes - MATLAB legend (16)

Specify Legend Font Size and Color

Open Live Script

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

Add legend to axes - MATLAB legend (17)

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

lgd.NumColumns = 2;

Add legend to axes - MATLAB legend (18)

Input Arguments

collapse all

label1,...,labelNLabels (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')

labelsLabels (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'}))

subsetData series to include in legend
vector of graphics objects

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

targetTarget for legend
Axes object | PolarAxes object | GeographicAxes object | standalone visualization

Target for legend, 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 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..

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

Legend location with respect to the axes, specified as one ofthe 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 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 propertyto display the legend in a custom location.

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

orntOrientation
'vertical' (default) | 'horizontal'

Orientation, specified as one of these values:

  • 'vertical' — Stack the legenditems vertically.

  • 'horizontal' — List thelegend items side-by-side.

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

bkgdLegend box display
'boxon' (default) | 'boxoff'

Legend box display, 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')

vsblLegend visibility
'hide' | 'show' | 'toggle'

Legend visibility, specified as one of these values:

  • 'hide' — Hide the legend.

  • 'show' — Show the legend or create a legend if one does not exist.

  • 'toggle' — Toggle the legend visibility.

Example: legend('hide')

Name-Value Arguments

Specify optional pairs of arguments as Name1=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, see Legend Properties.

NumColumnsNumber 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 toview 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

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

Algorithms

  • Recalling the legend function does not reset legend properties, such as the location or orientation. If a legend exists, then the legend function updates the existing legend. An Axes object can have only one legend.

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

Version History

Introduced before R2006a

expand all

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

See Also

Functions

  • plot | hold | title | xlabel | ylabel | text

Properties

  • Legend Properties

Topics

  • Add Legend to Graph

MATLAB Command

You clicked a link that corresponds to this MATLAB command:

 

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Add legend to axes - MATLAB legend (21)

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

Americas

  • América Latina (Español)
  • Canada (English)
  • United States (English)

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom (English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
  • 日本 (日本語)
  • 한국 (한국어)

Contact your local office

Add legend to axes - MATLAB legend (2025)

FAQs

How do you add a legend to a graph in MATLAB? ›

Set the DisplayName property as a name-value pair when calling the plotting functions. Then, call the legend command to create the legend. Legends automatically update when you add or delete a data series. If you add more data to the axes, use the DisplayName property to specify the labels.

How to manipulate legend in MATLAB? ›

To add a legend title, set the String property of the legend text object. To change the title appearance, such as the font style or color, set legend text properties. For a list, see Text Properties. plot(rand(3)); lgd = legend('line 1','line 2','line 3'); lgd.

How to put two legends in MATLAB? ›

Direct link to this answer
  1. t = 0:0.1:5;
  2. y = sin(t);
  3. z = cos(t);
  4. figure; hold on;
  5. for i = 1:2.
  6. p1(i) = plot(t, y,'r');
  7. p2(i) = plot(t, z,'b');
  8. end.
Feb 22, 2023

How to control legend in MATLAB? ›

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 .

How do you add a legend to a graph? ›

Click the chart, and then click the Chart Design tab. Click Add Chart Element > Legend. To change the position of the legend, choose Right, Top, Left, or Bottom. To change the format of the legend, click More Legend Options, and then make the format changes that you want.

Why is Matlab ignoring extra legend entries? ›

The warning "Ignoring extra legend entries" happens if you call legend() with more names than there are lines in your axes. In this case, it is related to your use of "hold on".

How to add a title to a legend in MATLAB? ›

Answers (1)
  1. legh = legend('line y = x');
  2. t = get(legh, 'Title');
  3. set(t, 'String', 'hello')
Dec 5, 2023

How do you change the legend in MATLAB scope? ›

On the Scope tab, the Configuration section allows you to modify the scope. The Legend button turns the legend on or off. When you show the legend, you can control which signals are shown. If you click a signal name in the legend, the signal is hidden from the plot and shown in grey on the legend.

How do I keep the legend outside the plot in MATLAB? ›

Legend = legend('Legend','Location','northoutside'); The vertical distance between the edge of the plot axes and the legend actually depends on the zoom level. Compare the attachments: fig1 (default zoom) with fig2 (zoomed a bit). Thus, it seems MATLAB automatically adjusts this vertical distance.

What is the limit of legend in MATLAB? ›

Accepted Answer

Legends are currently limited to no more than 50 entries. Usually in plots with more than 50 features, the plot is so cluttered and the legend is so large that it is more advisable to select just a few key items to display in the legend.

Can you have two legends on a map? ›

On the "map" visual you are only able to add one legend which is a color legend. Often times you need two legends. Several other BI tools like Tableau provide the option to have a legend based on "Shapes" and a legend based on "color".

How do I get rid of extra legends in MATLAB? ›

Below are two ways to remove a legend from a plot:
  1. Use the "findobj" function to find the legend(s) and the "delete" function to delete them: % Find and delete the legend. lgd = findobj('type', 'legend') ...
  2. If you do not want to delete the legend, you can turn off the legend's visibility: set(lgd(idx), 'visible', 'off')
Mar 26, 2016

Why do we use legend in MATLAB? ›

legend associates strings with the objects in the Axes in the same order that they are listed in the Axes Children property. By default, the legend annotates the current Axes. MATLAB displays only one legend per Axes. legend positions the legend based on a variety of factors, such as what objects the legend obscures.

How do you not include in legend in MATLAB? ›

One can suppress a legend entry for a line object h by executing h. HandleVisibility='off' or h. Annotation. LegendInformation.

How to skip one legend in MATLAB? ›

1- Select the curve you don't want have legend. 2- Go to the "more properties" (while the curve is still selected). 3- Turn "HandleVisibility" off.

How do I add a legend to a line graph in Matplotlib? ›

To create a legend in Matplotlib, you can use the legend() function after plotting your data. This function adds a legend to your plot, which helps to identify different data series.

How to add legend to contour matlab? ›

clegendm( C , h ) adds a legend specifying the contour line heights, C , to the current map contour plot, h . clegendm( C , h , loc ) places the legend in a specified location. clegendm(___, unitstr ) appends a string unitstr to each entry in the legend.

How do you add a legend to a count plot? ›

The easiest is to use hue= with the same variable as x= . You'll need to set dodge=False as by default a position is reserved for each x - hue combination. Note that when you aren't using hue , no legend is added as the names and colors are given by the x tick labels.

How to write legend in matlab for loop? ›

To make multiple figures each with a different legend you can use a for loop like this.
  1. % Multiple plots using for loop.
  2. ledgName = {'n1';'n2';'n3';'n4';'n5'}
  3. for k = 1:1:5.
  4. figure(k)
  5. plot(someData(:,k));
  6. legend(sprintf('%s', ledgName{k}),'Location','southeast'))
  7. end.
May 4, 2019

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Laurine Ryan

Last Updated:

Views: 5931

Rating: 4.7 / 5 (57 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Laurine Ryan

Birthday: 1994-12-23

Address: Suite 751 871 Lissette Throughway, West Kittie, NH 41603

Phone: +2366831109631

Job: Sales Producer

Hobby: Creative writing, Motor sports, Do it yourself, Skateboarding, Coffee roasting, Calligraphy, Stand-up comedy

Introduction: My name is Laurine Ryan, I am a adorable, fair, graceful, spotless, gorgeous, homely, cooperative person who loves writing and wants to share my knowledge and understanding with you.