Holding legend on a Matlab plot inside a loop

37 ビュー (過去 30 日間)
Amal Elawad
Amal Elawad 2017 年 1 月 7 日
コメント済み: Amal Elawad 2017 年 1 月 9 日
Hello, I have multiple plots to do using "hold all" and a for loop. However, I want to also add a legend every time I generate a new plot while keeping the old legends. How can I do that? Part of my code is as follows:
------------------------------
figure
subplot(2,2,1)
plot(t,H(1,:)), xlabel('t [s]'), ylabel('H [m]')
for i =2:n
% holds old plot for multi-line plots
hold all
plot(t,H(i,:)), xlabel('t [s]'), ylabel('H [m]')
end
Thanks in advance :)

採用された回答

Image Analyst
Image Analyst 2017 年 1 月 7 日
Make a cell array and then call legend with it on every iteration.
H = rand(5, 20);
[rows, columns] = size(H);
t = 1 : columns;
subplot(2,2,1)
plot(t,H(1,:))
grid on;
xlabel('t [s]')
ylabel('H [m]')
legendText = {'Plot #1'};
for k = 2 : rows
% holds old plot for multi-line plots
hold all
plot(t,H(k,:));
legendText{k} = sprintf('Plot #%d', k);
legend(legendText);
drawnow; % Force screen refresh.
end
  1 件のコメント
Amal Elawad
Amal Elawad 2017 年 1 月 9 日
It works! Thanks a lot :)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLegend についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by