How do I add plots to a legend in a loop?

조회 수: 67 (최근 30일)
MathWorks Support Team
MathWorks Support Team 2016년 2월 19일
답변: MathWorks Support Team 2016년 2월 19일
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?

채택된 답변

MathWorks Support Team
MathWorks Support Team 2016년 2월 19일
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개)

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

제품


릴리스

R2015a

Community Treasure Hunt

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

Start Hunting!

Translated by