How to add independent legends to each plot

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

回答(1 个)

Voss
Voss 2022-2-18
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 个评论
ROBIN KUMAR
ROBIN KUMAR 2022-2-18
编辑:ROBIN KUMAR 2022-2-18
it didn't workout, it requires the names in legend(lines,names) also to be updated, that's what originally the problem is.
It's the same thing. Any other way out to this problem, as in the solution provided, the same issue is there. It requires the names to be edited and that's what i really don't want as for a big program, i cannot track each of the name individually and edit under legend(lines,names);.
Voss
Voss 2022-2-18
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.

请先登录,再进行评论。

类别

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