Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent specific plot entry from being displayed on a MATLAB plot legend

Tags:

plot

matlab

I need to prevent a specific plot entry from being displayed on a Matlab plot legend.

Sample:

% x and y are any plot data
for i=1:5
    plot(x,y);
    plot(x2,y2,'PleaseNoLegend!'); % I need to hide this from legend
end
legend('show');

Is there any flag I can set inside the plot command so this specific entry doesn't show up in legend?

like image 537
Pedro77 Avatar asked Nov 30 '16 22:11

Pedro77


2 Answers

You can use the semi-documented function called hasbehavior, that allows you to ignore individual plots in a legend after you issued the plot command.

figure;
hold on;
for i=1:5
    plot(x,y);
    h = plot(x2,y2);
    hasbehavior(h,'legend',false);
end
legend('show');

The fact that it's semi-documented suggests that it could break sooner or later in a newer MATLAB version, so use with care. It might still be a convenient choice for certain applications.

As @stephematician noted, this MATLAB built-in is also unavailable in Octave, which might be another reason why the other answers are preferable.

like image 58

You can achieve that by setting the 'HandleVisibility' property to 'off'. Note that this hides the handles of those plots to all functions, not just to legend.

For example,

hold on
for k = 1:3
    x = 1:10;
    y = rand(1,10);
    x2 = x;
    y2 = y + 2;
    plot(x,y);
    plot(x2,y2,'--','HandleVisibility','off'); % Hide from legend
end
legend('show')

produces the graph

enter image description here

like image 22
Luis Mendo Avatar answered Nov 15 '22 19:11

Luis Mendo