Holding legend on a Matlab plot inside a loop

32 views (last 30 days)
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 :)

Accepted Answer

Image Analyst
Image Analyst on 7 Jan 2017
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

More Answers (0)

Community Treasure Hunt

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

Start Hunting!