How can I add an automatic legend to a graph with 10+ lines?

5 views (last 30 days)
I'm trying to generate a graph that has potentially 50 lines on it. In terms of formatting, I only know of the command "legend('Title 1''Title 2'....'Title n'). Given the number of lines I need to plot, I was wondering if there was a way to generate these titles automatically so if I increase the number of lines I don't have to manually add more titles in the legend.

Answers (1)

Dev
Dev on 25 Feb 2025
Hi John,
We can automate the generation of legend titles for any given number of lines using a ‘for’ loop which iterates over the total number of lines we want to plot. To do so, we can create a cell array and loop over the same to store each title as a cell in this array. For more information on creating and working with cell arrays, kindly refer to the below documentation-
To store the title in each cell, we can use the sprintf’ function in MATLAB. More details on the same can be referred below-
For further reference, below is a dummy code snippet which helps add legend titles to a graph having 10 lines (can be customized using the variable ‘n’).
% No. of lines to plot
n = 10;
figure;
% Hold the plot to overlay all lines
hold on;
% Generate and plot the lines
for i = 1:n
% Plot each line with some random data (replace this with actual data)
plot(rand(1, 10)); % Replace with your data or plotting function
end
% Automatically generate legend titles
legendLabels = cell(1, n); % Cell array to hold the legend labels
for i = 1:n
legendLabels{i} = sprintf('Title %d', i); % Automatically generate titles like 'Title 1', 'Title 2', etc.
end
% Set the legend
legend(legendLabels);
In the code above, we provide the titles stored in the ‘legendLabels’, which is a cell array, to the legend function which shows the titles for all 10 plotted lines, please refer to the code output above for your reference.
I hope this matches your expectations.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!