legend inside a For loop
128 views (last 30 days)
Show older comments
Hello All,
I am trying to have a plot legend update after each iteration but I am having a hard time coming up with a solution. I have tried different techniques but nothing has worked so far.
Basically, I would like to have the legend print all values of "n". For example, Fin = n1, Fin=n2, etc. Using the provided code, I only get the legend for the last value of "n". Any suggestions would be greatly appreciated.
for n = 0:n_fins_inter:n_fins;
plot(array.Velocity_Plot(array.Nf_Plot==n),array.Pres_Drop_Plot((array.Nf_Plot==n)))
legend({sprintf('fin =%f\n',n)},'Location','southeast')
hold on
end
Thank you.
0 Comments
Answers (2)
Walter Roberson
on 4 May 2019
for n = 0:n_fins_inter:n_fins;
dn = sprintf('fin =%f', n);
plot(array.Velocity_Plot(array.Nf_Plot==n),array.Pres_Drop_Plot((array.Nf_Plot==n)), 'DisplayName', dn);
hold on
end
legend('show', 'Location', 'southwest')
0 Comments
John Doe
on 4 May 2019
Edited: John Doe
on 4 May 2019
Hello,
Not quite sure what your end goal is here, multiple figures with different legends or 1 figure with many legends.
To make multiple figures each with a different legend you can use a for loop like this.
% Multiple plots using for loop
ledgName = {'n1';'n2';'n3';'n4';'n5'}
for k = 1:1:5
figure(k)
plot(someData(:,k));
legend(sprintf('%s', ledgName{k}),'Location','southeast'))
end
To plot all of the data on the same figure you don't have to use a for loop. I have offered to options one with and without a for loop.
Tip: The legend should be outside of the for loop.
% Without a for loop
ledgName = {'n1';'n2';'n3'}
figure(1)
plot(xdata(:,1),ydata(:,1),xdata(:,2),ydata(:,2),xdata(:,3),ydata(:,3)) % and so on
legend(ledgName)
title('A Title')
xlabel('X Axis')
ylabel('Y Axis')
%With a for loop
figure(1)
hold on
ledgName = {'n1';'n2';'n3';'n4';'n5'}
for k = 1:5
plot(x,someData(:,k))
end
legend(ledgName)
% If you don't want to use a cell array for legend names then use this. But this is pointless
legend('N1','N2','N3')
To create a cell array for your legend using a for loop per your comment below:
for k = 1:8
names{k} = sprintf('N%d',k)
end
3 Comments
See Also
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!