How do I add plots to a legend in a loop?
13 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
MathWorks Support Team
am 19 Feb. 2016
Beantwortet: MathWorks Support Team
am 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?
Akzeptierte Antwort
MathWorks Support Team
am 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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Legend finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!