A MATLAB plot can contain several lines, curves, or data series, yet a reader may struggle to identify what each one represents. Different colors and line styles help, but they do not always provide enough information on their own. That is where the MATLAB legend function becomes useful.
The legend function creates a labeled key that identifies the data series in a graph. You can use it to name plotted lines, distinguish experimental results, identify mathematical functions, and make scientific visualizations easier to interpret. MATLAB gives you control over legend labels, position, orientation, colors, fonts, mathematical notation, and automatic updates.
Whether you are creating a simple two-line graph or preparing a multi-series figure for a research paper, understanding the legend function helps you produce clearer and more professional plots.
What Is the MATLAB Legend Function?
The MATLAB legend function adds a legend to a chart or graph. A legend displays descriptive labels alongside symbols, line styles, or markers that represent the plotted data series.
For example, imagine plotting two mathematical functions:
- A sine wave.
- A cosine wave.
Without a legend, readers must identify the curves by their colors or line patterns. Adding a legend with the labels Sine Wave and Cosine Wave makes the graph easier to understand.
The basic command is:
legend('Sine Wave', 'Cosine Wave');
MATLAB creates a legend containing the two labels and associates them with the plotted objects.
The function works with many types of MATLAB visualizations, including:
- Line plots.
- Scatter plots.
- Bar charts.
- Area charts.
- Surface and other 3D plots.
- Plots containing multiple graphical objects.
You can create a basic legend with one command or return a legend object to customize its properties individually.
MATLAB Legend Syntax
The legend function supports several syntax forms. Each form serves a different purpose, depending on whether you want to supply labels, select specific graphics objects, control the legend’s appearance, or manage its visibility.
1. Basic Syntax
The following are the commonly used syntax forms:
legend
Creates a legend using the DisplayName properties of the plotted objects.
legend(label1, label2, ..., labelN)
Creates a legend using the labels you provide.
legend(labels)
Uses a cell array, string array, or character matrix containing the legend labels.
legend(subset, labels)
Creates a legend for selected graphics objects.
legend(target, ...)
Creates or modifies a legend for a specified axes or supported visualization instead of using the current axes.
lgd = legend(...)
Returns the legend object so you can modify its properties.
legend('off')
Deletes the legend from the current axes.
You can combine the label syntax with name-value arguments to set the location, orientation, font size, and other properties.
2. Understanding the Legend Object
When MATLAB creates a legend, it creates a Legend graphics object. Assigning that object to a variable gives you direct access to its properties.
For example:
lgd = legend('Dataset 1', 'Dataset 2');
lgd.FontSize = 12;
lgd.FontWeight = 'bold';
Here, lgd represents the legend object. You can use dot notation to change its appearance or behavior without creating another legend.
This approach is especially useful when you need to apply several formatting options to the same legend.
How to Create a Basic Legend in MATLAB
The simplest way to add a legend is to plot your data first and then provide a label for each plotted series.
Consider the following example.
x = 0:0.1:10;
y1 = sin(x);
y2 = cos(x);
plot(x, y1);
hold on;
plot(x, y2);
hold off;
legend('Sine Wave', 'Cosine Wave');
How This Code Works
x = 0:0.1:10creates a vector of values from 0 to 10.y1 = sin(x)calculates the sine values.y2 = cos(x)calculates the cosine values.- The first
plotcommand draws the sine wave. hold onallows MATLAB to retain the first plot when another series is added.- The second
plotcommand draws the cosine wave in the same axes. hold offends the multiple-plot operation.legendadds labels to identify both curves.
The labels follow the order of the plotted graphics objects. The first label identifies the first plotted series, and the second label identifies the second series.
Tip: Make sure that the number and order of your labels match the plotted objects. Incorrect ordering can cause a legend to identify the wrong curve.
Creating a MATLAB Legend Using the DisplayName Property
When working with several plotted series, manually entering all the labels inside the legend function can become difficult to maintain.
MATLAB provides the DisplayName property as an alternative. You can assign a name directly to each plotted object and then call legend without supplying labels again.
This method is particularly useful when your plotting commands are spread across multiple sections of a script.
Example: Using DisplayName
x = linspace(0, 2*pi, 200);
plot(x, sin(x), 'DisplayName', 'Sine Wave');
hold on;
plot(x, cos(x), 'DisplayName', 'Cosine Wave');
hold off;
legend;
MATLAB reads the DisplayName property from each plotted series and uses those values as the legend labels.
Why Use DisplayName?
The DisplayName approach offers several practical benefits:
- You define each label alongside the corresponding plotting command.
- You do not need to maintain a separate list of labels.
- The legend can use the assigned names when new data series are added.
- Your plotting code becomes easier to edit and organize.
- You reduce the risk of mismatching labels and plotted objects.
If a plotted object does not have a DisplayName value, MATLAB can use a default label such as data1 or data2.
For scripts with multiple figures or changing datasets, assigning meaningful DisplayName values is a reliable way to manage legends.
How to Add a Legend to Specific Plot Objects
You do not always need every plotted object to appear in the legend.
For example, a graph might contain two experimental measurements, a reference line, and a threshold line. You may want the legend to identify only the experimental measurements.
MATLAB allows you to select specific graphics objects by using their handles.
Example: Include Only Selected Lines
x = 0:0.1:10;
y1 = sin(x);
y2 = cos(x);
y3 = tanh(x);
h = plot(x, y1, x, y2, x, y3);
legend(h(1), 'Sine Wave');
The plot function returns graphics handles in h. The expression h(1) selects the first plotted line.
MATLAB creates a legend containing only the selected object.
Example: Include Two Lines but Exclude Another
x = 0:0.1:10;
y1 = sin(x);
y2 = cos(x);
y3 = exp(-x/5);
h = plot(x, y1, x, y2, x, y3);
legend(h([1 3]), {'Sine Wave', 'Exponential Curve'});
Here:
h(1)represents the first plotted line.h(3)represents the third plotted line.h([1 3])selects both objects.- The legend displays only the labels associated with those two objects.
This technique is useful when you need additional reference lines or supporting graphics without adding unnecessary entries to the legend.
Remember: The order of labels must match the order of the selected handles.
How to Change MATLAB Legend Position
A legend should be easy to find without hiding important information in the graph. MATLAB provides several predefined locations that let you position it inside or outside the plotting area.
You can control its location by using the Location property.
Basic Location Syntax
legend('Sine Wave', 'Cosine Wave', 'Location', 'northwest');
This places the legend in the upper-left corner of the axes.
Common MATLAB Legend Locations
| Location | Position | Typical use |
|---|---|---|
north | Inside at the top | Wide graphs |
south | Inside at the bottom | When the upper region contains important data |
east | Inside on the right | Compact charts |
west | Inside on the left | When the right side is crowded |
northeast | Upper-right corner | Default position for 2D axes |
northwest | Upper-left corner | When data occupies the right side |
southeast | Lower-right corner | When data occupies the upper region |
southwest | Lower-left corner | When data occupies the upper-right region |
northoutside | Above the axes | Labels that should not cover data |
southoutside | Below the axes | Graphs with space beneath the plot |
eastoutside | Outside on the right | Long labels or several entries |
westoutside | Outside on the left | When the right side must remain available |
best | Automatically selected inside position | When you want MATLAB to reduce overlap |
bestoutside | Automatically selected outside position | When the legend should remain outside the data area |
MATLAB supports additional corner-based outside positions, such as northeastoutside, northwestoutside, southeastoutside, and southwestoutside.
1. Place the Legend in the Upper-Right Corner
legend('Dataset 1', 'Dataset 2', 'Location', 'northeast');
This is the standard placement for many 2D plots.
2. Place the Legend Outside the Graph
legend('Dataset 1', 'Dataset 2', 'Location', 'eastoutside');
This places the legend to the right of the axes. It is useful when your plotted lines or markers occupy most of the graph.
3. Let MATLAB Choose the Best Location
legend('Dataset 1', 'Dataset 2', 'Location', 'best');
MATLAB chooses an available position inside the axes where the legend is expected to conflict least with the plotted data.
The best option is convenient for quick plots. For publication figures, inspect the result manually because automatic placement does not guarantee that every data point remains unobstructed.
How to Change MATLAB Legend Orientation
By default, MATLAB displays legend entries vertically. Each label appears on a separate row.
You can change the orientation to horizontal when the graph has several entries or when you need a compact legend above or below the plot.
Vertical Legend
legend('Series 1', 'Series 2', 'Series 3', ...
'Orientation', 'vertical');
The labels appear one below another.
Horizontal Legend
legend('Series 1', 'Series 2', 'Series 3', ...
'Orientation', 'horizontal');
The labels appear side by side.
When Should You Use Each Orientation?
A vertical legend works well when:
- Your graph contains several long labels.
- You want the labels arranged in a familiar reading order.
- There is enough space beside the plot.
- You are displaying multiple experimental series.
A horizontal legend works well when:
- Your graph contains only a few entries.
- You want to place the legend above or below the plot.
- You are preparing a wide figure.
- You want to reduce the vertical space occupied by the legend.
How to Add Multiple Columns to a MATLAB Legend
Graphs containing several data series can produce tall legends. Multiple columns offer a practical way to arrange the entries into a more compact layout.
Use the NumColumns property.
Example: Two-Column Legend
x = linspace(0, 10, 100);
plot(x, sin(x), 'DisplayName', 'Series 1');
hold on;
plot(x, sin(2*x), 'DisplayName', 'Series 2');
plot(x, sin(3*x), 'DisplayName', 'Series 3');
plot(x, sin(4*x), 'DisplayName', 'Series 4');
hold off;
lgd = legend;
lgd.NumColumns = 2;
MATLAB arranges the legend entries into two columns.
You can change the number of columns according to the number of entries and the space available.
lgd.NumColumns = 3;
The actual number of displayed columns can be smaller than the requested value if there are not enough entries.
Tip: Use multiple columns for wide figures and presentations. For a graph with long labels, check that the resulting layout does not make the legend excessively wide.
How to Customize MATLAB Legend Appearance
MATLAB provides several formatting properties that let you adjust the legend’s appearance.
You can change:
- Font size.
- Font name.
- Font weight.
- Font angle.
- Text color.
- Background color.
- Border color.
- Border visibility.
The recommended approach is to obtain the legend object and modify the required properties.
Example: Customize Legend Font and Colors
x = 0:0.1:10;
plot(x, sin(x), 'DisplayName', 'Sine Wave');
hold on;
plot(x, cos(x), 'DisplayName', 'Cosine Wave');
hold off;
lgd = legend;
lgd.FontSize = 12;
lgd.FontWeight = 'bold';
lgd.FontAngle = 'italic';
lgd.TextColor = 'blue';
lgd.Color = [1 1 1];
lgd.EdgeColor = 'black';
Each property controls a different part of the legend.
1. Change Legend Font Size
Use FontSize to increase or decrease the size of the legend text.
lgd = legend;
lgd.FontSize = 14;
The value is specified in points.
A larger font can make labels easier to read in presentations and printed figures. Choose a size that remains consistent with the other text in your graph.
2. Change Font Weight
Use FontWeight to control the thickness of the legend text.
lgd.FontWeight = 'bold';
Available options include:
'normal''bold'
Bold text can help distinguish legend labels from the background, especially in figures containing several data series.
3. Change Font Angle
Use FontAngle to display legend labels in normal or italic text.
lgd.FontAngle = 'italic';
The available options are 'normal' and 'italic'.
4. Change Font Name
Use FontName to select a supported font installed on your computer.
lgd.FontName = 'Arial';
You can choose another available font according to your figure’s design requirements. MATLAB also supports the special value 'FixedWidth' for a fixed-width font.
5. Change Legend Text Color
The TextColor property controls the color of the legend labels.
lgd.TextColor = 'red';
You can use standard color names, RGB triplets, or hexadecimal color codes.
For example:
lgd.TextColor = [0 0 1];
This sets the text color to blue.
You can use a custom hexadecimal value as well:
lgd.TextColor = '#0066CC';
RGB components must use values from 0 to 1.
6. Change Legend Background Color
Use the Color property to change the legend’s background.
lgd.Color = [1 1 1];
This sets a white background.
You can use a named color or hexadecimal color code:
lgd.Color = '#F2F2F2';
A light background can make the legend labels easier to read when they overlap visually with complex plotted data.
7. Change Legend Border Color
Use the EdgeColor property to change the outline color.
lgd.EdgeColor = 'red';
For a custom border color, use an RGB triplet:
lgd.EdgeColor = [0.2 0.2 0.2];
You can remove the visible outline by setting:
lgd.EdgeColor = 'none';
8. Remove the Legend Border
The Box property controls whether MATLAB displays a box around the legend.
lgd.Box = 'off';
To restore the box, use:
lgd.Box = 'on';
You can use this property when you want a cleaner-looking graph with less visual clutter.
How to Add a Title to a MATLAB Legend
A legend title helps explain what its entries represent. It is particularly useful when labels describe different categories, measurement conditions, or experimental groups.
Use the Title.String property.
Example: Add a Legend Title
x = 0:0.1:10;
plot(x, sin(x), 'DisplayName', 'Sine');
hold on;
plot(x, cos(x), 'DisplayName', 'Cosine');
hold off;
lgd = legend;
lgd.Title.String = 'Mathematical Functions';
MATLAB displays Mathematical Functions above the legend entries.
You can customize the title’s appearance too.
lgd.Title.FontSize = 12;
lgd.Title.FontWeight = 'bold';
The title has its own text properties, so you can format it separately from the legend labels.
MATLAB Legend Interpreter: TeX and LaTeX Formatting
MATLAB supports mathematical notation inside legend labels. This is useful when your plots contain scientific equations, Greek symbols, superscripts, subscripts, or mathematical variables.
The Interpreter property controls how MATLAB processes legend text.
MATLAB provides three options:
'tex': Uses MATLAB’s supported subset of TeX formatting. This is the default.'latex': Uses LaTeX mathematical formatting.'none': Displays the label as literal text without interpreting special markup.
1. Use TeX Formatting
TeX formatting allows you to add superscripts, subscripts, Greek letters, and other mathematical symbols.
Example:
x = 0:0.1:10;
plot(x, x.^2, 'DisplayName', 'x^{2}');
hold on;
plot(x, sqrt(x), 'DisplayName', '\alpha_{1}');
hold off;
legend('Interpreter', 'tex');
Some useful TeX formatting commands include:
| Format | MATLAB syntax | Meaning |
|---|---|---|
| Superscript | x^{2} | x squared |
| Subscript | x_{1} | x with subscript 1 |
| Alpha | \alpha | Greek alpha |
| Beta | \beta | Greek beta |
| Gamma | \gamma | Greek gamma |
| Pi | \pi | Greek pi |
| Infinity | \infty | Infinity symbol |
| Greater than or equal to | \geq | Mathematical comparison |
| Less than or equal to | \leq | Mathematical comparison |
For example:
legend({'x^{2}', '\alpha_{1}', '\beta_{2}'}, ...
'Interpreter', 'tex');
This produces legend labels containing mathematical expressions.
2. Use LaTeX Formatting
For more advanced mathematical notation, MATLAB supports the LaTeX interpreter.
plot(1:10, (1:10).^2, 'DisplayName', '$x^2$');
hold on;
plot(1:10, sqrt(1:10), 'DisplayName', '$\sqrt{x}$');
hold off;
legend('Interpreter', 'latex');
The LaTeX labels must use dollar signs to identify inline mathematical expressions.
You can use this option for equations, fractions, integrals, roots, and other supported mathematical expressions.
3. Display Labels Without Mathematical Interpretation
Sometimes you need MATLAB to display special characters exactly as written.
Use:
legend('x^{2}', '\alpha_{1}', 'Interpreter', 'none');
MATLAB displays the characters literally rather than formatting them as mathematical expressions.
How to Control Automatic Legend Updates
MATLAB can automatically update a legend when you add new graphics objects to an axes.
This behavior is controlled by the AutoUpdate property.
By default, automatic updating is enabled.
Example: Automatic Legend Updating
x = 0:0.1:10;
plot(x, sin(x), 'DisplayName', 'Sine Wave');
hold on;
lgd = legend;
plot(x, cos(x), 'DisplayName', 'Cosine Wave');
hold off;
The new cosine curve can appear in the legend automatically because its DisplayName property is defined.
Disable Automatic Updating
If you do not want MATLAB to add new plotted objects to an existing legend, set AutoUpdate to 'off'.
x = 0:0.1:10;
plot(x, sin(x), 'DisplayName', 'Sine Wave');
hold on;
lgd = legend;
lgd.AutoUpdate = 'off';
plot(x, cos(x), 'DisplayName', 'Cosine Wave');
hold off;
The legend retains its existing entries when the new cosine curve is added.
This is useful when you want to control which graphics objects appear in the legend.
Note: Disabling automatic updating does not prevent MATLAB from updating the legend when a plotted object is deleted. This behavior applies to MATLAB releases from R2022b onward.
How to Change the Order of MATLAB Legend Entries
The order of legend entries normally follows the order of the plotted graphics objects. MATLAB provides the Direction property to control the display order.
Normal Order
lgd = legend;
lgd.Direction = 'normal';
The first entry appears at the top of a vertical legend.
Reverse Order
lgd.Direction = 'reverse';
The order is reversed, placing the last entry at the top.

The Direction property is available from MATLAB R2023b.
For stacked bar charts and area charts, MATLAB uses a reversed default order in newer releases to match the visual stacking order. You can explicitly set Direction when you need a particular arrangement.
How to Adjust the Width of Legend Icons
A legend contains text and graphic icons. The space allocated to the icons can affect the total width of the legend box.
MATLAB provides the IconColumnWidth property to control this space.
lgd = legend;
lgd.IconColumnWidth = 10;
The property value is measured in points.
A smaller value can shorten certain legend icons and reduce unnecessary spacing. You can adjust the value according to the length of your labels and the appearance of your plotted line styles.
The IconColumnWidth property was introduced in MATLAB R2024b.
How to Position a Legend in a Tiled Chart Layout
MATLAB’s tiledlayout function lets you arrange several axes within a single figure. You can position a legend in one of the surrounding layout tiles instead of placing it over an individual plot.
This approach is useful when you are preparing multiple related charts.
Example: Place a Legend to the Right of a Tiled Layout
x = linspace(0, 2*pi, 200);
t = tiledlayout(1, 2);
ax1 = nexttile;
plot(ax1, x, sin(x), 'DisplayName', 'Sine');
hold(ax1, 'on');
plot(ax1, x, cos(x), 'DisplayName', 'Cosine');
hold(ax1, 'off');
ax2 = nexttile;
plot(ax2, x, exp(-x/5).*sin(x), ...
'DisplayName', 'Damped Sine');
lgd = legend(ax1);
lgd.Layout.Tile = 'east';
The first tile contains the sine and cosine curves. The second tile contains the damped sine curve. The legend is assigned to the right-side tile of the tiled layout.
The Layout.Tile property can accept positions such as 'north', 'south', 'east', and 'west', as well as tile numbers.
This makes it easier to maintain a consistent figure layout when working with several related charts.
How to Set a Custom Legend Position
Predefined positions are suitable for most graphs. Some figures need a more precise location.
You can use the Position property to specify the legend’s placement and dimensions.
lgd = legend;
lgd.Position = [0.65 0.70 0.20 0.15];
The four values represent:
- Left position.
- Bottom position.
- Width.
- Height.
The default position units are normalized units. The values are measured relative to the legend’s container, usually the figure.
You can change the measurement units by using the Units property.
lgd.Units = 'pixels';
The available units include:
'normalized''inches''centimeters''characters''points''pixels'
Setting a custom Position changes the legend’s Location property to 'none'.
Important: The Position property does not control placement when the legend belongs to a TiledChartLayout object. For tiled layouts, use the Layout.Tile property instead.
How to Hide, Show, or Remove a MATLAB Legend
You may need to remove a legend temporarily or make it visible again. MATLAB offers several commands for controlling legend visibility.
Remove a Legend
legend('off');
This deletes the existing legend from the current axes.

Hide a Legend
legend('hide');
This hides the legend without deleting it.
Show a Hidden Legend
legend('show');
This displays a hidden legend again.
Toggle Legend Visibility
legend('toggle');
This switches the visibility of the legend.
You can control visibility by using the legend object too:
lgd = legend;
lgd.Visible = 'off';
To make it visible again:
lgd.Visible = 'on';
The difference between hiding and deleting matters when you need to preserve the legend’s existing configuration.
Common MATLAB Legend Problems and Their Solutions
Even though creating a legend is straightforward, a few common issues can affect the result. Understanding their causes can save time when editing MATLAB scripts.
1. The Legend Shows Incorrect Labels
Problem: The legend labels do not correspond to the correct plotted lines.
Cause: The labels are assigned in a different order from the plotted objects.
Solution: Check the order of your plotting commands and legend labels. You can use DisplayName to assign each label directly to the corresponding graphics object.
plot(x, y1, 'DisplayName', 'First Dataset');
hold on;
plot(x, y2, 'DisplayName', 'Second Dataset');
hold off;
legend;
2. MATLAB Displays data1 or data2 Instead of Custom Labels
Problem: The legend contains generic names such as data1, data2, or similar default labels.
Cause: The plotted graphics objects do not have meaningful DisplayName properties.
Solution: Assign descriptive names during plotting.
plot(x, y1, 'DisplayName', 'Experimental Data');
hold on;
plot(x, y2, 'DisplayName', 'Calculated Data');
hold off;
legend;
3. The Legend Covers Important Plot Data
Problem: The legend blocks a curve, marker, or important data point.
Cause: The legend is placed inside the axes.
Solution: Move it outside the graph or use automatic placement.
legend('Location', 'eastoutside');
You can try:
legend('Location', 'best');
Inspect the result to make sure the chosen position is suitable.
4. New Lines Automatically Appear in the Legend
Problem: Additional plotted lines keep appearing as legend entries.
Cause: The AutoUpdate property is enabled.
Solution: Disable automatic updates.
lgd = legend;
lgd.AutoUpdate = 'off';
You can then manage the legend entries manually.
5. The Legend Is Too Large
Problem: The legend occupies too much space in the figure.
Cause: Long labels, large fonts, or a single-column arrangement can increase the legend’s dimensions.
Solution: Try reducing the font size or creating multiple columns.
lgd = legend;
lgd.FontSize = 10;
lgd.NumColumns = 2;
A horizontal orientation can be another useful option.
6. Mathematical Symbols Appear as Ordinary Text
Problem: MATLAB displays expressions such as x^2 without the expected superscript formatting.
Cause: The selected interpreter does not match the label format.
Solution: Set the interpreter to 'tex' or 'latex'.
legend({'x^{2}', '\alpha_{1}'}, ...
'Interpreter', 'tex');
7. The Legend Appears on the Wrong Axes
Problem: MATLAB creates or updates a legend on a different plot than the one you intended.
Cause: The legend command operates on the current axes by default.
Solution: Specify the target axes explicitly.
legend(ax1, 'Sine Wave', 'Cosine Wave');
This is particularly helpful when using subplot, tiledlayout, or figures containing multiple axes.
Best Practices for Creating Professional MATLAB Legends
A useful legend should identify each data series without competing with the plotted information. The following practices help keep your figures readable.
Use Descriptive Labels
Avoid labels such as Line 1, Line 2, or Data A when more meaningful descriptions are available.
Choose labels that explain what the plotted data represents.
For example:
- Measured Temperature
- Predicted Temperature
- Experimental Result
- Simulation Output
- Reference Curve
Keep Labels Short
Long descriptions can make the legend unnecessarily wide or tall. Use concise labels that retain their meaning.
You can explain additional information in the figure caption or surrounding text.
Place the Legend Where It Does Not Obstruct Data
Select a position based on the shape of the graph and the distribution of its data points.
Outside positions are useful when the plotting area is crowded.
Maintain Consistent Formatting
Use similar font sizes, font weights, and label styles across related figures. Consistency makes it easier to compare different plots.
Use DisplayName for Larger Scripts
When plotting multiple series across different sections of a script, assigning names through DisplayName makes the code easier to maintain.
Avoid Unnecessary Legend Entries
A reference line, grid-related object, or decorative graphic does not always need a legend label. Use graphics handles to include only the objects that contribute meaningful information.
Check the Final Figure
Inspect the legend after changing its position, font, or orientation. Check that labels are readable and that the legend remains suitable when the figure is resized or exported.
MATLAB Legend Function: Quick Reference
The following table provides frequently used commands and their purposes.
| Task | MATLAB command |
|---|---|
| Create a basic legend | legend('A','B') |
| Use DisplayName values | legend |
| Set legend location | legend('Location','northwest') |
| Place legend outside | legend('Location','eastoutside') |
| Set horizontal orientation | legend('Orientation','horizontal') |
| Set vertical orientation | legend('Orientation','vertical') |
| Create multiple columns | legend('NumColumns',2) |
| Change font size | lgd.FontSize = 12 |
| Set bold text | lgd.FontWeight = 'bold' |
| Change text color | lgd.TextColor = 'red' |
| Change background color | lgd.Color = [1 1 1] |
| Remove border | lgd.Box = 'off' |
| Add legend title | lgd.Title.String = 'My Title' |
| Disable automatic updates | lgd.AutoUpdate = 'off' |
| Reverse legend order | lgd.Direction = 'reverse' |
| Hide legend | legend('hide') |
| Show legend | legend('show') |
| Remove legend | legend('off') |
Frequently Asked Questions About MATLAB Legend
1. What Does the Legend Function Do in MATLAB?
The legend function creates a labeled key that identifies the plotted data series in a graph. It helps readers distinguish between different curves, lines, markers, and other graphical objects.
2. How Do I Add a Legend to a MATLAB Plot?
First, create your plot using the plot function. Then call legend with the labels you want to display.
plot(x, y1);
hold on;
plot(x, y2);
hold off;
legend('First Line', 'Second Line');
3. How Do I Automatically Generate Legend Labels in MATLAB?
Assign a DisplayName value to each plotted object.
plot(x, y1, 'DisplayName', 'First Dataset');
hold on;
plot(x, y2, 'DisplayName', 'Second Dataset');
hold off;
legend;
MATLAB uses the assigned display names as legend entries.
4. How Do I Change the Legend Position in MATLAB?
Use the Location property.
legend('Location', 'northeast');
You can replace 'northeast' with another supported location, such as 'southwest', 'northoutside', or 'eastoutside'.
5. How Do I Make a Horizontal Legend in MATLAB?
Use the Orientation property.
legend('A', 'B', 'C', 'Orientation', 'horizontal');
This arranges the labels side by side.
6. How Do I Increase the Legend Font Size?
First, obtain the legend object. Then assign a larger value to its FontSize property.
lgd = legend;
lgd.FontSize = 14;
7. How Do I Remove a Legend From a MATLAB Plot?
Use:
legend('off');
This deletes the legend from the current axes.
8. How Do I Add a Title to a Legend?
Use the Title.String property.
lgd = legend;
lgd.Title.String = 'Experimental Results';
9. Can I Display Only Selected Lines in a Legend?
Yes. Use the graphics handles returned by plotting commands.
h = plot(x, y1, x, y2, x, y3);
legend(h([1 3]), {'First Line', 'Third Line'});
This adds only the first and third plotted objects to the legend.
10. What Is the Difference Between Legend and DisplayName in MATLAB?
legend is the function that creates and manages the labeled key. DisplayName is a property assigned to an individual graphics object that supplies its legend label.
You can define DisplayName values when plotting and then call legend to display them automatically.
11. Can I Customize the MATLAB Legend Background?
Yes. Use the Color property of the legend object.
lgd = legend;
lgd.Color = [0.9 0.9 0.9];
This example sets a light gray background.
12. Does MATLAB Automatically Update Legends?
Yes. Automatic updating is enabled by default. New graphics objects can be added to the legend when they are plotted.
To prevent new objects from appearing automatically, use:
lgd = legend;
lgd.AutoUpdate = 'off';
13. Can I Use Greek Letters in MATLAB Legend Labels?
Yes. MATLAB’s default TeX interpreter supports Greek letters and several other mathematical symbols.
legend('\alpha', '\beta', '\gamma', ...
'Interpreter', 'tex');
You can use the LaTeX interpreter for more advanced mathematical formatting.
Make Your MATLAB Plots Easier to Understand
A well-designed MATLAB legend does more than identify colored lines. It gives readers the information they need to interpret a graph without guessing which curve represents a particular measurement, function, or experimental result.
Once you understand the legend function, you can control how labels are created, choose which graphics objects appear, position entries around the axes, and adjust the formatting to suit your figure. Properties such as DisplayName, Location, Orientation, NumColumns, FontSize, TextColor, and AutoUpdate give you direct control over the result.
For everyday plotting, a simple command such as legend('Sine Wave','Cosine Wave') may be enough. For larger projects, using the returned legend object and assigning meaningful DisplayName values makes your scripts easier to maintain.
The best legend is one that makes the plotted information immediately understandable. Give each series a meaningful label, choose a position that preserves the data, and keep the formatting consistent. Your MATLAB figures will be easier to read, compare, present, and share.
Resources:
https://www.mathworks.com/help/matlab/ref/legend.html
https://www.mathworks.com/help/matlab/ref/matlab.graphics.illustration.legend-properties.html
