How do I add plots to a legend in a loop?
11 views (last 30 days)
Show older comments
MathWorks Support Team
on 19 Feb 2016
Answered: MathWorks Support Team
on 19 Feb 2016
I want to add plots to a legend in each iteration of a loop but if I use the "legend" function I only get a legend for the last plot I added.
How do I incrementally add plots to the same legend?
Accepted Answer
MathWorks Support Team
on 19 Feb 2016
There are multiple ways to add legends to a plot.
1) Set the 'DisplayName' property of each plot. The 'DisplayName' is the string shown in the legend. When you create a legend MATLAB will add all elements that have set the 'DisplayName' property to the legend. Refer to the example below.
t = linspace(0,2*pi,100);
figure;
axes('NextPlot','add');
for freq=1:3
plot( t, cos(freq*t),'DisplayName', ['cos(' num2str(freq) 't)']);
%uncomment if you want to see change each loop
%legend('show')
%pause;
%legend('off')
end
legend('show'); %create/show legend
2) Save the plot handles and legend labels while you loop and add them all to the legend at the end.
t = linspace(0,2*pi,100);
figure;
axes('NextPlot','add');
n=3;
plotHandles = zeros(1,n);
plotLabels = cell(1,n);
for freq=1:n
plotHandles(freq) = plot( t, cos(freq*t) );
plotLabels{freq} = ['cos(' num2str(freq) 't)'];
end
legend(plotHandles, plotLabels);
0 Comments
More Answers (0)
See Also
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!