How do I ask the legend to add labels for multiple graphs

1 visualización (últimos 30 días)
John McCormick
John McCormick el 18 de Nov. de 2015
Respondida: Voss el 25 de Sept. de 2024
I want to generate a plot with potentially 100 series on it. Is there a way that I can suitably attach the legend (with title 1: title n) without typing the name of each series in the legend command? The titles would be increasing sequentially (legend('Title1''Title2''Titlen'))

Respuestas (2)

ag
ag el 25 de Sept. de 2024
Hi John,
To achieve this you can automate the process of adding legends to your plot without manually typing each label by using a counter variable.
The below code snippet demonstrates how to achieve this:
% Sample data
x = linspace(0, 2*pi, 100);
% Create a figure
figure;
% Initialize an empty cell array to store legend labels
legendLabels = cell(1, 10);
% Loop to plot 100 series
for i = 1:10
% Generate some example data
y = sin(x + i/10);
% Plot the data
plot(x, y);
hold on; % Hold the plot to overlay multiple series
% Create a legend label and store it in the array
legendLabels{i} = sprintf('Title%d', i);
end
% Add the legend using the generated labels
legend(legendLabels);
% Add title and labels
title('Plot with 10 Series');
xlabel('x');
ylabel('Function values');
% Release the hold
hold off;
For more details, please refer to the following MathWorks documentation:
Hope this helps!

Voss
Voss el 25 de Sept. de 2024
legend("Title"+(1:n))

Community Treasure Hunt

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

Start Hunting!

Translated by