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.

legend();

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)

FAQs

What are legends in plot 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.

What is plot legend ()? ›

Matplotlib.pyplot.legend() function is a utility given in the Matplotlib library for Python that gives a way to label and differentiate between multiple plots in the same figure. The attribute Loc in legend() is used to specify the location of the legend. The default value of loc is loc= “best” (upper left).

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.

Can you 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: add a second (exatly equal) set of axes to the figure. make this axes invisible, so you don't see it later in the plot. add two "helping - lines", one solid and one dotted.

What is the purpose of a legend on a graph? ›

Most charts use some kind of a legend to help readers understand the charted data. Whenever you create a chart in Excel, a legend for the chart is automatically generated at the same time.

What does legend mean plot? ›

A legend is a key to a plot that labels data by color, pattern, and symbol. This example shows a basic legend. displaying two plots on one graph.

When should you include a legend on a plot? ›

Answer. If your graph has more than one line, then you should always include a legend. Graphs should try to be self-explanatory, and provide enough information that someone unfamiliar with it, can look at it and understand what the data represents and what each line is describing.

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.

What is a key vs legend on a graph? ›

To be clear, a map legend is another word for map key. Just like your house key is a useful tool to open your house, a legend and map key are both the keys of a map. Nowadays, the map key definition is the same for a map key and map legend. They are the same tool with two different names.

How do you put a legend inside a plot? ›

Control legend position with legend.

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 hide the legend in a plot 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

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.

What does legend in MATLAB do? ›

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

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.

What is the maximum legend entries in MATLAB? ›

Unfortunately, according to the MathWorks Support Team, MATLAB legends are limited by default to 50 entries.

What does legends mean in diagram? ›

A legend is an area of a diagram (graph) that identifies colors or patterns assigned to categories from a table. A legend is usually used when there are a large number of categories in a table. Example. Given the table of information below, one possible circle graph is shown without a legend.

What is a legend in a bar plot? ›

A legend is a tool to help explain a graph. You are most commonly going to want to add one to a bar chart where you have several data series. You'll also want to add one to a line or scatter plot when you have more than one series. Essentially you use a legend to help make a complicated plot more understandable.

What is plot legends in Mathematica? ›

PlotLegend. is an option for Plot, ListPlot, and related functions that assigns text to lines in a 2D plot to create a legend for that plot.

What is legend in scatter plot? ›

To create a scatter plot with a legend one may use a loop and create one scatter plot per item to appear in the legend and set the label accordingly. The following also demonstrates how transparency of the markers can be adjusted by giving alpha a value between 0 and 1.

References

Top Articles
Putnam.schoology.com
Ao Sun Math
Woodward Avenue (M-1) - Automotive Heritage Trail - National Scenic Byway Foundation
Cottonwood Vet Ottawa Ks
Obor Guide Osrs
How to know if a financial advisor is good?
Erskine Plus Portal
Best Cheap Action Camera
Self-guided tour (for students) – Teaching & Learning Support
Urinevlekken verwijderen: De meest effectieve methoden - Puurlv
LeBron James comes out on fire, scores first 16 points for Cavaliers in Game 2 vs. Pacers
Cool Math Games Bucketball
‘Accused: Guilty Or Innocent?’: A&E Delivering Up-Close Look At Lives Of Those Accused Of Brutal Crimes
800-695-2780
Buy PoE 2 Chaos Orbs - Cheap Orbs For Sale | Epiccarry
Hilo Hi Craigslist
Theresa Alone Gofundme
Log in or sign up to view
Skyward Login Jennings County
Virginia New Year's Millionaire Raffle 2022
Noaa Ilx
Barber Gym Quantico Hours
Wbiw Weather Watchers
Kcwi Tv Schedule
Georgia Cash 3 Midday-Lottery Results & Winning Numbers
Empire Visionworks The Crossings Clifton Park Photos
Ontdek Pearson support voor digitaal testen en scoren
Harbor Freight Tax Exempt Portal
Sam's Club Gas Price Hilliard
Pipa Mountain Hot Pot渝味晓宇重庆老火锅 Menu
UPC Code Lookup: Free UPC Code Lookup With Major Retailers
Puerto Rico Pictures and Facts
Green Bay Crime Reports Police Fire And Rescue
Steven Batash Md Pc Photos
Lichen - 1.17.0 - Gemsbok! Antler Windchimes! Shoji Screens!
Mp4Mania.net1
Etowah County Sheriff Dept
Space Marine 2 Error Code 4: Connection Lost [Solved]
2700 Yen To Usd
Frommer's Philadelphia & the Amish Country (2007) (Frommer's Complete) - PDF Free Download
Davis Fire Friday live updates: Community meeting set for 7 p.m. with Lombardo
Ezpawn Online Payment
Nina Flowers
Random Animal Hybrid Generator Wheel
Babykeilani
Candise Yang Acupuncture
UNC Charlotte Admission Requirements
Spn 3464 Engine Throttle Actuator 1 Control Command
Fishing Hook Memorial Tattoo
Les BABAS EXOTIQUES façon Amaury Guichon
Yoshidakins
Latest Posts
Article information

Author: Barbera Armstrong

Last Updated:

Views: 5655

Rating: 4.9 / 5 (79 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Barbera Armstrong

Birthday: 1992-09-12

Address: Suite 993 99852 Daugherty Causeway, Ritchiehaven, VT 49630

Phone: +5026838435397

Job: National Engineer

Hobby: Listening to music, Board games, Photography, Ice skating, LARPing, Kite flying, Rugby

Introduction: My name is Barbera Armstrong, I am a lovely, delightful, cooperative, funny, enchanting, vivacious, tender person who loves writing and wants to share my knowledge and understanding with you.