How to make a legend for a plot within a for loop

조회 수: 11 (최근 30일)
Sue MM
Sue MM 2018년 7월 18일
편집: Adam Danz 2021년 1월 6일
HI! I am currently plotting a graph (with 3 different entries) and I want to create a legend within the for loop that would show each iteration for the 3 different I/O how should I approach this? The current legend i have does not update with each iteration
  댓글 수: 2
Will Fritz
Will Fritz 2018년 7월 18일
Hi, can you provide a little more context to your issue. For example, do you have three different plots? Or just one where the legend changes every iteration? Any code provided to help frame this would be appreciated
Sue MM
Sue MM 2018년 7월 18일
편집: dpb 2018년 7월 18일
I have 2 bode plots that I am plotting on the same figure within the for loop.
figure(1)
bode(sys1)
grid on
hold on
margin(sys2)
I am trying to create a legend that will distinguish between each iteration of the bode plot that it is printing

댓글을 달려면 로그인하십시오.

채택된 답변

Adam Danz
Adam Danz 2018년 7월 18일
편집: Adam Danz 2021년 1월 6일
It's strange that bode() doesn't seem to output the plot handles.
Anyway, here are two options using fake data; the first is best if your code can be adapted to it.
Fake data
H1 = tf([1 0.1 7.5],[1 0.12 9 0 0]);
H2 = tf([1 0.3 7.5],[1 0.12 9 0 0]);
H3 = tf([1 0.5 7.5],[1 0.12 9 0 0]);
Option 1: no loop
bode(H1, 'r', H2, 'b', H3, 'k')
legend({'H1', 'H2', 'H3'})
Option 2: with loop * you have to 'hold' your axes!
values = {H1, H2, H3};
H = values{1};
figure()
bode(H)
axh = findall(gcf, 'type', 'axes');
hold(axh(3),'on') % upper axis
hold(axh(2),'on') % lower axis
for i = 2:numel(values)
bode(values{i})
end
legend(axh(3), {'H1', 'H2', 'H3'}) % upper axis
legend(axh(2), {'H1', 'H2', 'H3'}) % lower axis

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by