Plot Legends in MATLAB (2024)

Plot Legends in MATLAB (1)

Plot legends are essential for properly annotating your figures. Luckily, MATLAB/Octave include the legend() function which provides some flexible and easy-to-use options for generating legends. In this article, I cover the basic use of the legend() function, as well as some special cases that I tend to use regularly.

The source code for the included examples can be found in the GitHub repository.

The legend() function in MATLAB/Octave allows you to add descriptive labels to your plots. The simplest way to use the function is to pass in a character string for each line on the plot. The basic syntax is: legend( ‘Description 1’, ‘Description 2’, … ).

For the examples in this section, we will generate a sample figure using the following code.

x = 0 : 0.1 : ( 2pi ); 
plot( x, sin( x ), 'rx', 'linewidth', 2 );
hold on;
plot( x, cos( x/3 ) - 0.25, 'bs', 'linewidth', 2 );
plot( x, cos( 4x )/3, '^g', 'linewidth', 2 );
hold off;
xlim( [ 0, 2*pi ] );
grid on;
title( 'Sample Plot' );
set( gca, 'fontsize', 16 );

A legend can be added with the following command.

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

In addition to specifying the labels as individual character strings, it is often convenient to collect the strings in a cell array. This is most useful when you are programmatically creating the legend string.

legStr = { 'Line 1', 'Line 2', 'Line 3' };
legend( legStr );

For convenience, this method will be used for the rest of the examples. The resulting figure looks like this.

Plot Legends in MATLAB (4)

By default the legend has been placed in the upper, right corner; however, the ‘location’ keyword can be used to adjust where it is displayed. The location is selected using a convention based on the cardinal directions. The following keywords can be used: north, south, east, west, northeast, northwest, southeast, southwest. The following code snippet would place the legend in the center top of the plot.

legend( legStr, 'location', 'north' );

Similarly, all of the other keywords can be used to place the legend around the plot. The following animation illustrates all of the different keywords.

Plot Legends in MATLAB (5)

The keyword ‘outside’ can also be appended to all of the locations to place the legend outside of the plot. The next image shows an example with the legend on the east outside.

legend( legStr, 'location', 'eastoutside' );
Plot Legends in MATLAB (6)

In addition to the setting the location, the legend() function also allows you to set the orientation of the legend to either ‘vertical’ (default) or ‘horizontal’. The following example will position the legend at the bottom, outside of the plot, with a horizontal orientation.

legend( legStr, 'orientation', 'horizontal', ...
'location', 'southoutside' );
Plot Legends in MATLAB (7)

Another convenient way to add the legend labels is to set the “DisplayName property on the lines as they are plotted. This can be done during the plot() call or using set() on the handle. In both cases, after you have set the properties, you need to all legend() without any arguments to toggle the legend on.

The syntax for the plot() should look like this.

plot( x, sin( x ), 'rx', 'linewidth', 2, 'DisplayName', 'Line1' );
hold on;
plot( x, cos( x/3 ) - 0.25, 'bs', 'linewidth', 2, 'DisplayName', 'Line2' );
plot( x, cos( 4*x )/3, '^g', 'linewidth', 2, 'DisplayName',
'Line3' );
hold off;

The syntax for the set() should like this.

% Plot the lines
h1 = plot( x, sin( x ), 'rx', 'linewidth', 2, 'DisplayName', 'Line1' );
hold on;
h2 = plot( x, cos( x/3 ) - 0.25, 'bs', 'linewidth', 2, 'DisplayName', 'Line2' );
h3 = plot( x, cos( 4*x )/3, '^g', 'linewidth', 2, 'DisplayName', 'Line3' );
hold off;
% Update the display names
set( h1, 'DisplayName', 'Line1' );
set( h2, 'DisplayName', 'Line2' );
set( h3, 'DisplayName', 'Line3' )

The legend would then be toggled on by calling legend() without any input arguments.


The resulting plot would be the same as the first example shown earlier in the tutorial.

Similar to all of the other graphics objects, the legend properties can be adjusted using the set() and get() functions. The following code will capture the legend handle and then set a few of the legend properties. In this particular example, the location is set to northeast, the orientation is set to vertical, the font size is set to 16, and the box outline is removed.

hl = legend( legStr ); % save the legend handle
set( hl, 'orientation', 'vertical' ); % set the orientation
set( hl, 'location', 'northeast' ); % set the location
set( hl, 'fontsize', 16 ); % set the font size
set( hl, 'box', 'off' ); % turn off the box lines
Plot Legends in MATLAB (8)

There are number of other properties that can be set on the legend object. Simply call get(hl) in the command window to display them all. One of the most convenient of these properties is the ‘position’ property. The position property allows us to set the exact position of the legend by specifying its horizontal origin (h0), vertical origin (v0), width (w) and height (h). If you are not familiar with setting the position property on graphics object, you can see a brief description here.

Whenever you are working with subplots or GUIs, it is often necessary to specify an exact location for the legend. This ensures that your legend does overlap with other elements or create weird spacing. Building on the previous example, we can mock up an example GUI that includes our plot, a couple of buttons, and a legend that is manually placed on the figure.

% Set up the subplot
set( f, 'units', 'normalized' );
a = subplot( 'position', [ 0.1, 0.1, 0.5, 0.8 ] );
% Build our sample plot
x = 0 : 0.1 : ( 2*pi );
plot( x, sin( x ), 'rx', 'linewidth', 2 );
hold on;
plot( x, cos( x/3 ) - 0.25, 'bs', 'linewidth', 2 );
plot( x, cos( 4*x )/3, '^g', 'linewidth', 2 );
hold off;
xlim( [ 0, 2*pi ] );
grid on;
title( 'Sample Plot' );
set( a, 'fontsize', 16 );
% Add some buttons
a = uicontrol( f, 'units', 'normalized', 'position', [ 0.7, 0.7, 0.2, 0.1 ], ...
'style', 'pushbutton', 'string', 'Press Me' );
a = uicontrol( f, 'units', 'normalized', 'position', [ 0.7, 0.5, 0.2, 0.1 ], ...
'style', 'pushbutton', 'string', 'Click Here' );
% Add a legend manually
hl = legend( legStr );
set( hl, 'fontsize', 16 );
set( hl, 'position', [ 0.74 0.25 0.12721 0.14310 ] );
Plot Legends in MATLAB (9)

Rather than providing character strings for all of the lines on the plot, it is possible to specify an array of specific line objects that should be included in the legend. I find this especially useful for situations where you only need to draw attention to a few lines on the plot. I tend to use this feature when I am plotting a large number of examples or realizations of some kind and want to overlay and highlight some statistics or metrics.

The following example creates some random data and calculates some statistics from it. All of the realizations are plotted as thin gray lines and the statistics are overlaid as much thicker colored lines.

% Generate some random data and calculate a few statistics
t = sqrt( 0.5 ) * randn( 100, 500 );
ts = sort( t, 2 );
t10 = ts( :, floor( 0.10 * size( t, 2 ) ) );
t90 = ts( :, floor( 0.90 * size( t, 2 ) ) );
% Plot realizations as thin gray lines and statistics as thicker, colored lines
plot( t, 'linewidth', 0.2, 'color', [0.5 0.5 0.5] );
hold on;
l1 = plot( mean( t, 2 ), 'linewidth', 4, 'color', [0, 1, 0] );
l2 = plot( t10, 'linewidth', 4, 'color', [1, 0, 0] );
l3 = plot( t90, 'linewidth', 4, 'color', [0, 0, 1] );
hold off;
grid on;
ylim( [-3, 3] );
title( 'Statistics' );
set( gca, 'fontsize', 16 );
% Add a legend to just the statistics
hl = legend( [ l1, l2, l3 ], 'Mean', '10th Prct', '90th Prct', ...
'orientation', 'horizontal', 'location', 'north' );
set( hl, 'fontsize', 16 );
Plot Legends in MATLAB (10)

The result is a pretty nice plot (in my opinion). If we didn’t pass in the line handles, then the legend() function would have tried to add a legend label to every single realization. There are certainly other use cases; however, this is a type of plot that I tend to make pretty frequently.

In this article, I covered several ways to use the legend() function in MATLAB/Octave. Here are a few key things to remember.

  • The legend labels can be passed in as individual character strings or as a cell array.
  • There a number of both position and orientation options that can be used to place the legend in certain parts of the figure.
  • The legend graphics handle can be used to directly set any of the legend properties, including manually setting the position anywhere in the figure.
  • Line graphics handles can be used to specify a subset of lines that will be labeled in the legend.

Happy coding!

Plot Legends in MATLAB (2024)


How to plot the legend 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 have two legends in MATLAB plot? ›

As far as I know, you can only have one legend-window for one set of axes in MATLAB, so the idea is:
  1. add a second (exatly equal) set of axes to the figure.
  2. make this axes invisible, so you don't see it later in the plot.
  3. add two "helping - lines", one solid and one dotted.
  4. make these helping - lines also invisible.
Nov 19, 2018

How do you add a legend title to a plot 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.

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

Direct link to this answer
  1. Each subplot is a unique axis. The legend command lets you specify the axis where the legend will be created:
  2. "LEGEND(AX,...) puts a legend on the axes with handle AX."
  3. So if you get the axis handles when you create the subplots you can then specify the legend for each subplot.
Feb 16, 2012

What is plot legend ()? ›

legend() A legend is used to describe elements for a particular area of a graph. Python has a function called legend() which is used to place a legend on the axis. The legend function has an attribute called loc which is used to denote the location of the legend.

How do you put a legend inside a plot? ›

You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.

How do I manually add a legend in MATLAB? ›

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. If you add or delete a data series from the axes, the legend updates accordingly.

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.

How to add 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.

How do you plot without a legend in Matlab? ›

Below are two ways to remove a legend from a plot:
  • 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') ...
  • 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

How do you set a legend outside a subplot? ›

In order to place the legend outside of the plot, let's say at the center of the right side, we need to do two things. First, we need to shrink the width of the plot so that the legend fits the figure. Then, we can use the bbox_to_anchor argument that offers a degree of control for manual legend placement.

How to write a legend for a graph? ›

4 Features of a Good Figure Legend:
  1. Title: A brief title that applies to the entire figure, including all panels. ...
  2. Materials and methods: A description of the techniques used. ...
  3. Results: A statement of the results that can be gleaned from the particular figure. ...
  4. Definitions: An explanation of features in the figure.
Dec 29, 2014

How to format a figure legend? ›

My top tips for how to write a figure legend

Refer to the Figure Directly: Use 'Figure 1 shows…' instead of 'the following figure shows…'. Keep it Concise: While being descriptive, keep the caption brief and to the point. Use Past Tense: You are describing work that has been completed.

Top Articles
Latest Posts
Article information

Author: Moshe Kshlerin

Last Updated:

Views: 5564

Rating: 4.7 / 5 (57 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Moshe Kshlerin

Birthday: 1994-01-25

Address: Suite 609 315 Lupita Unions, Ronnieburgh, MI 62697

Phone: +2424755286529

Job: District Education Designer

Hobby: Yoga, Gunsmithing, Singing, 3D printing, Nordic skating, Soapmaking, Juggling

Introduction: My name is Moshe Kshlerin, I am a gleaming, attractive, outstanding, pleasant, delightful, outstanding, famous person who loves writing and wants to share my knowledge and understanding with you.