MATLAB Plot Legends: In the world of data visualization, few tools are as powerful and versatile as MATLAB. One of its standout features is the ability to create plots that are both informative and aesthetically pleasing. However, as any MATLAB user knows, the true beauty of a plot lies in how the data is presented — and that includes the legend.
In this article, we’ll explore how to enhance your MATLAB plots with legends that incorporate variable values dynamically. Imagine you want to label your plots using input variables like A_1 or B_2, where both the letter and number are dynamic based on your data. We’ll walk through step-by-step instructions on how to achieve this using MATLAB plot legends with variable inputs.
Understanding MATLAB Legends
Before we dive into the specifics of concatenating variables for legends, let’s quickly review what a legend in MATLAB is and how it functions. Legends are essential in MATLAB because they allow you to identify different data series in a plot. Without a clear legend, a plot might become confusing, especially when there are multiple data sets.
A legend in MATLAB is simply a small box that labels the lines or markers in your plot. You can customize the legend to include any information, such as plot labels or data values. Typically, the legend is added using the legend() function, like so:
plot(x, y)
legend('Data Set 1')
plot(x, y)
legend('Data Set 1')
The Challenge: Variable Values in Legends
Now, let’s say you want to include more detailed, dynamic labels in your legend. Specifically, you want the labels to reflect variable values such as A_1, B_2, and so on, where A and B are letters, and 1 and 2 are numbers, based on the input arguments.
This is where things can get tricky. The legend function, by default, doesn’t allow you to directly incorporate variables within the string. However, fear not — MATLAB provides several methods to work around this limitation and achieve the desired result.

The Solution: Concatenate Variables for Legends
To dynamically create a legend with variable values, you need to combine the variables (letters and numbers) into a single string. This is where the concatenation operators come into play. MATLAB’s [] (square brackets) operator is perfect for this task, as it allows you to join variables or strings.
Here’s a basic example to demonstrate the process:
% Define the variables
letter1 = 'A';
number1 = 1;
letter2 = 'B';
number2 = 2;
% Create some plots
figure()
hold on
h1 = plot(1:10); % Plot 1
h2 = plot(5:15); % Plot 2
% Add the legend with variable values
legend([letter1,'_',num2str(number1)], [letter2,'_',num2str(number2)]);
Dealing with Non-Integer Numbers
So, you’re happy with your dynamic legends, but what happens when the numbers are not integers? You might run into a situation where A_0.5 shows up as just A_0. This happens because MATLAB’s num2str function by default trims decimal places for values that can be represented as whole numbers.
The solution here is simple. If you want to keep the decimal places intact, you can specify the number of decimal places to display using sprintf instead of num2str. For instance, if you want to always display one decimal place, you can modify the legend creation line as follows:
legend(sprintf('%s_%.1f', letter1, number1), sprintf('%s_%.1f', letter2, number2));
A Step-by-Step Guide to Creating Dynamic Legends
Let’s walk through the full process to create a plot with a legend that reflects dynamic variables, including both integer and non-integer values.
Define Your Variables
The first step is to define the variables you’ll use in your legend. These could be any letters and numbers that represent the different data sets in your plot.
matlabCopyEditletter1 = 'A'; % Define letter 1
number1 = 0.5; % Define number 1
letter2 = 'B'; % Define letter 2
number2 = 2.75; % Define number 2
Create Your Plot
Next, you’ll create the plot itself. In this example, we’ll use some simple data, but your data could be anything — the key is that you’re plotting multiple data sets.
matlabCopyEdit% Create figure and hold it for multiple plots
figure()
hold on
% Create the first plot
h1 = plot(1:10, rand(1, 10), 'r'); % Random data for plot 1
% Create the second plot
h2 = plot(5:15, rand(1, 11), 'b'); % Random data for plot 2
Add the Dynamic Legend
Now that you’ve got your plot, it’s time to add the dynamic legend that incorporates the values of the variables. Use the sprintf function to format the variables as strings.
matlabCopyEditlegend(sprintf('%s_%.1f', letter1, number1), sprintf('%s_%.2f', letter2, number2));
Here, %s is used for the letter, and %.1f or %.2f controls the decimal places for the number. In this example, the first plot will have the legend A_0.5, and the second plot will have the legend B_2.75.
Common Pitfalls and How to Avoid Them
Legends Overlapping with Data
Sometimes, when you add a legend to a plot, it can overlap with the actual data, especially if the plot is complex. To prevent this, you can adjust the location of the legend by specifying a position argument in the legend() function:
matlabCopyEditlegend('Location', 'northeast');
This moves the legend to the upper-right corner of the plot, avoiding overlap with the data points.
Misformatted Numbers
If you encounter issues with misformatted numbers, especially with floating point precision, make sure to use sprintf with the appropriate format specifiers (%.2f, %.3f, etc.). This will give you full control over how the numbers are displayed in the legend.
Frequently Asked Questions
What is a plot legend in MATLAB?
A plot legend in MATLAB is a descriptive label that helps identify different data series or graphical elements in a plot. It associates each line, marker, or object in the plot with a label, making it easier to understand the data being visualized.
How do I add a basic legend to a plot in MATLAB?
To add a basic legend, use the legend function. For example:
matlabCopyEditx = 1:10;
y1 = x.^2;
y2 = x.^3;
plot(x, y1, x, y2);
legend('x squared', 'x cubed');
This will create a legend with two entries: “x squared” and “x cubed.”
Can I use variables in MATLAB plot legends?
Yes, you can use variables in MATLAB legends by concatenating strings or using num2str to convert numerical values into strings. For example:
matlabCopyEdita = 5;
b = 10;
plot(x, y1, x, y2);
legend(['y = ' num2str(a)], ['y = ' num2str(b)]);
This will display the legends as “y = 5” and “y = 10.”
How do I dynamically update plot legends with variables?
To dynamically update the legend, you can modify the legend after changing the data or variables:
matlabCopyEdita = 5;
b = 10;
plot(x, y1, x, y2);
legend(['y = ' num2str(a)], ['y = ' num2str(b)]);
% Later, if a and b change:
a = 7;
b = 12;
legend(['y = ' num2str(a)], ['y = ' num2str(b)]);
Can I add variable text along with static text in the legend?
Yes, you can mix variable text and static text. Use string concatenation to include both. For example:
matlabCopyEdita = 5;
plot(x, y1);
legend(['y = x^2 (a = ' num2str(a) ')']);
This will show “y = x^2 (a = 5)” as the legend.
How do I handle legends for multiple plots with different data sizes in MATLAB?
When plotting multiple datasets with different sizes, MATLAB automatically adjusts the legend to match each data series. Ensure that each plot command has a corresponding label:
matlabCopyEditx = 1:10;
y1 = x.^2;
y2 = x(1:5).^3; % smaller dataset
plot(x, y1, x(1:5), y2);
legend('x squared', 'x cubed (short)');
Can I position the legend manually in a MATLAB plot?
Yes, you can manually position the legend by specifying the 'Position' property. For example:
matlabCopyEditlegend('show');
legend('Location', 'northeast'); % Automatic position
legend('Position', [0.5, 0.5, 0.1, 0.1]); % Custom position
How can I make a legend entry based on a variable’s value or condition?
You can create conditional legends based on the value of a variable:
matlabCopyEdita = 10;
if a > 5
legend('Value of a is greater than 5');
else
legend('Value of a is less than or equal to 5');
end
Can I change the font size and style of the legend in MATLAB?
Yes, you can customize the font size, style, and other properties using the legend function. For example:
matlabCopyEditlegend('x squared', 'x cubed');
legend('FontSize', 14, 'FontName', 'Arial', 'FontWeight', 'bold');
How can I add legends for plot types other than lines, such as scatter plots or bar graphs?
You can add legends for scatter plots, bar graphs, or other plot types similarly by associating each plot with a label. For example:
matlabCopyEditx = 1:10;
y = x.^2;
scatter(x, y);
legend('Scatter plot of y = x^2');
bar(x, y);
legend('Bar graph of y = x^2');
Conclusion
In this article, we’ve explored how to add dynamic legends to your MATLAB plots using variables for both letters and numbers. By concatenating these variables into strings and using sprintf for precise formatting, you can create more informative legends that reflect your data’s true values.
Remember, the legend is not just a decorative element of your plot. It’s a vital part of data visualization, helping others (and yourself) understand the context of the data presented. By mastering this technique, you can create plots that are both visually appealing and easy to interpret.
