Holding legend on a Matlab plot inside a loop

50 次查看(过去 30 天)
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

更多回答(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