How to Create Custom Legend in MATLAB (2024)

  1. Add Custom Legends Using the legend() Function in MATLAB
  2. Add Custom Legends Using the text() Function in MATLAB
  3. Conclusion
How to Create Custom Legend in MATLAB (1)

Creating clear and informative plots is a fundamental aspect of data visualization in MATLAB. Legends play a vital role in aiding the understanding of plotted data and providing context and clarity to the information being presented.

While MATLAB’s built-in legend() function is commonly used to add legends to plots, it has its limitations when it comes to customization. This article explores how to enhance legend customization using both the legend() and text() functions in MATLAB.

Add Custom Legends Using the legend() Function in MATLAB

The legend() function in MATLAB is a valuable tool used to add legends to a plot, aiding in the interpretation of data and enhancing the visualization. Its basic syntax is as follows:

legend('label1', 'label2', ...)
  • 'label1', 'label2', ...: These are the legend labels corresponding to the plotted data or any other custom labels you want to display. Each label is a string enclosed in single quotes.

However, it’s worth noting that the legend() function is designed to add a single legend to a plot. Attempting to add more than one legend using this function will result in a MATLAB error.

In order to overcome this limitation and add custom legends that aren’t directly related to the graphed data, a workaround involves adding more plots to the figure with undefined values. These additional plots serve as placeholders, allowing the inclusion of multiple legends.

Although the plots themselves won’t be visible due to their undefined values, the legends associated with them will be displayed.

Take a look at the example below:

t = 1:0.01:2;plot(cos(2*pi*t))hold onp(1) = plot(NaN,NaN);p(2) = plot(NaN,NaN);p(3) = plot(NaN,NaN);hold offlegend(p,'Cos1','Cos2','Cos3')

Output:

How to Create Custom Legend in MATLAB (2)

In this provided code, we begin by creating a time vector t using the colon operator, generating values from 1 to 2 with a step size of 0.01. Next, we plot a cosine wave using cos(2*pi*t), creating the main plot that we want to display.

To prepare for adding custom legends unrelated to this plot, we employ hold on, ensuring subsequent plots are added to the existing figure. Then, we generate three additional plots using plot(NaN,NaN), essentially creating dummy plots with undefined values.

These serve as placeholders to facilitate the addition of custom legends.

After setting up the placeholder plots, hold off is used to disable the hold state, allowing any subsequent plots to replace the current plot.

Finally, we utilize legend() with the placeholder plot handles p and assign custom labels 'Cos1', 'Cos2', and 'Cos3' to create the desired custom legends. The legends appear on the plot even though the placeholder plots themselves are not visible due to the undefined values.

This technique enables the creation of multiple legends associated with a single plot, offering flexibility in legend customization within MATLAB.

Add Custom Legends Using the text() Function in MATLAB

Adding custom legends to a plot can also be achieved using the text() function. This function allows you to insert text at specified coordinates on the plot.

The basic syntax for the text() function is as follows:

text(x, y, str)

Where:

  • x is the x-coordinate where the text will be placed.
  • y is the y-coordinate where the text will be placed.
  • str is the text string you want to display.

You can also specify additional optional parameters to customize the appearance of the text. Here’s an extended version of the syntax:

text(x, y, str, 'PropertyName', PropertyValue, ...)

Where:

  • 'PropertyName' is the name of the property you want to set (e.g., 'FontSize', 'Color', 'FontWeight', etc.).
  • PropertyValue is the value you want to set for the corresponding property.

You can include multiple property-value pairs to customize various aspects of the text, such as font size, color, rotation, etc. Let’s demonstrate this with an example.

Customize Text Properties

Note that you need to specify the x and y coordinates where you want the text to be placed. Ensure that these coordinates lie within the plot area; otherwise, the text won’t be visible.

t = 1:0.01:2;plot(cos(2*pi*t))t = text(100,0.8,'Cos1','FontSize',18,'Color','r');

Output:

How to Create Custom Legend in MATLAB (3)

In this example, a cosine wave is plotted, and the text() function is used to place the text Cos1 at coordinates (100, 0.8) with a font size of 18 and in red color.

You can further customize the appearance of the text by adjusting its properties, such as font size (FontSize) and color (Color).

Add Lines and Boxes

To enhance the legend, lines or boxes can be added. For example, you can add a blue line before the text and a black box around the text and the line:

t = 1:0.01:2;plot(cos(2*pi*t))tex = text(95,0.8,'{\color{blue} ---} Cos','FontSize',18,'Color','k','EdgeColor','k')

Output:

How to Create Custom Legend in MATLAB (4)

In this example, a blue line ({\color{blue} ---}) is added before the text, and a black box is drawn around both the line and the text.

Add Multiple Text Elements

Furthermore, you can add multiple texts at different positions on the plot, each with its styling. For instance, let’s add another text with a different line style, color, and a box:

t = 1:0.01:2;plot(cos(2*pi*t))tex1 = text(95,0.8,'{\color{blue} ---} Cos','FontSize',18,'Color','k','EdgeColor','k')tex2 = text(89,0.4,'{\color{red} *} Cosine','FontSize',18,'Color','g','EdgeColor','y')

Output:

How to Create Custom Legend in MATLAB (5)

This adds another text with a red asterisk (*) and the text Cosine with a green color and a yellow box.

Add Multiple Strings in the Same Box

Multiple strings can be added within the same box by organizing them in a cell array and passing it to the text() function. This allows for a more organized and visually appealing legend.

t = 1:0.01:2;plot(cos(2*pi*t))tex3 = text(89,0.2,{'{\color{red} *} Cosine','{\color{blue} ---} Cos'},'FontSize',18,'Color','g','EdgeColor','y');

Output:

How to Create Custom Legend in MATLAB (6)

By following these steps and customizing the properties, you can create informative and visually appealing legends for your MATLAB plots using the text() function. For more information and additional options, refer to the official MATLAB documentation on the text() function.

Conclusion

Customizing legends is essential for effectively conveying information in MATLAB plots.

While the legend() function provides a straightforward way to add legends, its limitation in handling multiple legends can be overcome using placeholder plots. By creating dummy plots and associating custom labels, you can achieve the desired multiple legends with ease.

Additionally, the text() function offers a flexible approach to custom legend creation, allowing for precise placement and style customization. By leveraging the capabilities of both functions, you can craft visually appealing and informative legends that complement your plots and enhance the overall understanding of the data being presented.

Whether you prefer the simplicity of legend() or the fine-grained control of text(), the ability to tailor your legends will undoubtedly elevate your data representation and storytelling capabilities.

How to Create Custom Legend in MATLAB (2024)

FAQs

How to make custom legends 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 modify 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 insert legend manually in MATLAB? ›

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

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

How do I add a custom legend in Plotly? ›

Adding Multiple Legends

Specify more legends with legend="legend3" , legend="legend4" and so on. In this example, the last two scatter traces display on the second legend, "legend2". On the figure's layout, we then position and style each legend.

How do I create a custom function in MATLAB? ›

To create a custom task function:
  1. On the Project tab, click the down arrow to expand the Tools gallery. ...
  2. Click Add and then select Add Using New Function. ...
  3. Specify a file name for the script and save the new file on the MATLAB path. ...
  4. Edit the function to perform the desired action on each file. ...
  5. Save the file.

How to add legend in MATLAB scope? ›

On the Scope tab, the Configuration section allows you to modify the scope.
  1. The Legend button turns the legend on or off. ...
  2. The Settings button opens the settings window which allows you to customize the data, axes, display settings, labels, and color settings.

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 do you insert a legend? ›

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 do you add a legend to a plot in MATLAB Python? ›

Matplotlib.pyplot.legend() in Python

The attribute Loc in legend() is used to specify the location of the legend. The default value of loc is loc= “best” (upper left). The strings 'upper left', 'upper right', 'lower left', and 'lower right' place the legend at the corresponding corner of the axes/figure.

How to put two legends in MATLAB? ›

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

What is the legend in Matlab plot? ›

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

How do you add a legend to a contour plot in 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 I create a custom legend in Powerpoint? ›

Customize a legend
  1. On the View menu, click Print Layout.
  2. Click the chart, and then click the Chart Design tab.
  3. Click Add Chart Element > Legend.
  4. To change the position of the legend, choose Right, Top, Left, or Bottom.

Can you have multiple legends in MATLAB? ›

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.

Top Articles
Latest Posts
Article information

Author: Greg Kuvalis

Last Updated:

Views: 5585

Rating: 4.4 / 5 (75 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Greg Kuvalis

Birthday: 1996-12-20

Address: 53157 Trantow Inlet, Townemouth, FL 92564-0267

Phone: +68218650356656

Job: IT Representative

Hobby: Knitting, Amateur radio, Skiing, Running, Mountain biking, Slacklining, Electronics

Introduction: My name is Greg Kuvalis, I am a witty, spotless, beautiful, charming, delightful, thankful, beautiful person who loves writing and wants to share my knowledge and understanding with you.