Legend inside for loop
이전 댓글 표시
Hello,
I want to generate single legend outside for the figure window for all subplots. I am doing plots inside a loop like this:
t,x and y are given datas
for i=1:10
figure()
subplot(2,2,i)
plot(x,y)
hold on
plot(t,y)
subplot(2,2,i)
plot(x,y-y')
hold on
% ........
legend('1','2,','3')
end
But i am still getting the legend on all plots.
any help is appreciated
Dan
댓글 수: 6
Adam Danz
2022년 8월 4일
This should produce an error since it appears that you are attempting to generate 10 suplots in a 2x2 grid. But since we don't see the rest of what's going on within the loop, I can't be sure.
It's unclear what the goals is and what the actual results are.
danel james
2022년 8월 4일
편집: danel james
2022년 8월 4일
Adam Danz
2022년 8월 4일
I must have missed the end. Thanks.
Adam Danz
2022년 8월 4일
Move figure out of the loop if you want all suplots within the same figure.
Move Legend out of the loop if you only want to create a legend for the last subplot.
danel james
2022년 8월 4일
답변 (1개)
Walter Roberson
2022년 8월 4일
for i=1:10
figure()
subplot(2,2,i)
H(3*i-2) = plot(x, y, 'displayname', i + "A");
hold on
H(3*i-1) = plot(t, y, 'displayname', i + "B");
subplot(2,2,i)
H(3*i) = plot(x, y-y', 'displayname', i + "C");
hold on
% ........
end
legend(H)
Are you wanting only 3 entries in the legend, total? If so then you would want to be explicit about the line colors, and you would legend(H(1:3))
댓글 수: 4
danel james
2022년 8월 4일
Walter Roberson
2022년 8월 4일
for i=1:10
subplot(2,5,i)
H(3*i-2) = plot(x, y, 'displayname', i + "A");
hold on
H(3*i-1) = plot(t, y, 'displayname', i + "B");
H(3*i) = plot(x, y-y', 'displayname', i + "C");
hold off
% ........
end
legend(H)
danel james
2022년 8월 4일
x = 1:10; y = rand(size(x));
for i=1:10
subplot(2,5,i)
H(3*i-2) = plot(x, y, 'displayname', i + "A");
hold on
H(3*i-1) = plot(x, y, 'displayname', i + "B");
H(3*i) = plot(x, y-y', 'displayname', i + "C");
hold off
% ........
end
legend(H)
What size is y? If y is a vector then y - y' creates a square matrix in which each element of y is subtracted from each other element of y; the result of plotting that would be multiple lines.
카테고리
도움말 센터 및 File Exchange에서 Legend에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
