How to add independent legends to each plot
5 views (last 30 days)
Show older comments
Dear all,
How can I add independent legends to each plot. Sometimes i need to turn off some plots and check rest, then it becomes hectic to again check which legend entry is to be turned off. And even if I omit (remove the corresponding entry), then how to get the same back? sometimes it's really important to turn different plots OFF and check the rest all, then the legends create problem. They're not updated properly and it just redistribute them in a sequence which are available (non-commented plots, turned ON plots).
Is there a way to turn only the corresponding legends OFF?
0 Comments
Answers (1)
Voss
on 18 Feb 2022
If you keep track of your line handles and their associated names for the legend, then it won't be too much trouble when you comment some out.
A run with 3 lines:
figure();
hold on
lines = [];
names = {};
lines(end+1) = plot(1:10);
names{end+1} = 'Slope = 1';
lines(end+1) = plot(2:2:12);
names{end+1} = 'Slope = 2';
lines(end+1) = plot(10:-2:0);
names{end+1} = 'Slope = -2';
legend(lines,names);
Another run with one of the lines commented out:
figure();
hold on
lines = [];
names = {};
lines(end+1) = plot(1:10);
names{end+1} = 'Slope = 1';
% lines(end+1) = plot(2:2:12);
% names{end+1} = 'Slope = 2';
lines(end+1) = plot(10:-2:0);
names{end+1} = 'Slope = -2';
legend(lines,names);
2 Comments
Voss
on 18 Feb 2022
If the names are like, 'Line 1', 'Line 2', Line 3', and when you comment out plotting line 2, then 'Line 3' should become 'Line 2', then, yes, you need to update the names and my solution doesn't cover that type of situation. Is that the situation your are in? If so, please share some code so that I might be able to offer useful advice.
Otherwise, associating a name to a line and then calling legend() with whatever lines were created along with their associated names should work well.
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!