How can I add a legend in a for loop?
3 views (last 30 days)
Show older comments
How do I add a legend in a for loop?
This is my code:
for ncol = 1: 4
plot(time{i,ncol}, knee_angle{i, ncol});
hold on;
plot(subjects(i,ncol,1),y_point_begin(i,ncol),'ro');
hold on;
plot(subjects(i,ncol,2),y_point_end(i,ncol),'k*');
xlabel('Time (s)');
ylabel('Knee Angle (rad)');
end
I want that in each plot there is legend with ncol and that ro and k* are given too. So for example the first time ncol is 3, this means that my legend would be as follows: 'Knee1', 'Knee2', 'Knee3', 'Begin', 'End'. If then ncol is 4 then I want 'Knee1', 'Knee2', 'Knee3', 'Knee4', 'Begin', 'End'.
Thank you in advance!
0 Comments
Accepted Answer
Rik
on 15 Dec 2020
The best way is probably to use the DisplayName input for plot. You would have to be a bit careful about the order in which your plots will appear in the legend. You might want to use a cell array to hold the handles and use legend([handle_array{:}]).
Just a side note: you don't need the second call to hold, as the NextPlot property will already be set to 'add'.
More Answers (0)
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!