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

1 回表示 (過去 30 日間)
John McCormick
John McCormick 2015 年 11 月 18 日
回答済み: Voss 2024 年 9 月 25 日
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'))

回答 (2 件)

ag
ag 2024 年 9 月 25 日
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 2024 年 9 月 25 日
legend("Title"+(1:n))

カテゴリ

Help Center および File ExchangeLegend についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by