How do I create a legend involving multiple plots created in a for loop?
조회 수: 44 (최근 30일)
이전 댓글 표시
I am trying to create a figure with 3 plots and a legend detailing what each plot is. Each plot is created in a for loop.
for j= 1:3
y = j;
figure(1);
plot(y);
hold on;
end
Thus, there will be 3 lines labeled in the legend. I appreciate any help that you all can provide!
댓글 수: 0
답변 (3개)
Adam Danz
2019년 4월 26일
편집: Adam Danz
2019년 4월 26일
Here are some demos you can follow.
Option 1: add legend labels when you call legend
figure()
axes
hold on
nLoops = 3;
ph = gobjects(1,nLoops);
for j= 1:nLoops
y = randn(10,1)+j;
ph(j) = plot(y, '-o');
end
legend(ph, {'first', 'second', 'third'})
Option 2: add legend labels within the loop
figure()
axes
hold on
nLoops = 3;
ph = gobjects(1,nLoops);
for j= 1:nLoops
y = randn(10,1)+j;
ph(j) = plot(y, '-o', 'DisplayName', sprintf('line %d',j));
end
legend(ph)
댓글 수: 4
Image Analyst
2019년 4월 27일
Try this:
figure()
hold on
numberOfLoops = 3;
for k = 1 : numberOfLoops
y = randn(10,1) + k;
plot(y, '.-', 'MarkerSize', 20, 'LineWidth', 2);
% Make up a string for this particular line plot.
legends{k} = sprintf('This is plot #%d', k);
end
legend(legends) % Display all the legend texts.
grid on;

댓글 수: 1
참고 항목
카테고리
Help Center 및 File Exchange에서 Legend에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!