How to show legend for only a specific subset of curves in the plotting?

I do not like storing the handle values, it becomes a mess when I have a lot of graphs in my figures. Therefore i found another solution.

t = 0 : 0.01 : 2 * pi;
s = sin(t);
c = cos(t);
m = -sin(t);
hold on;
plot(t, s, 'r', 'HandleVisibility','off'); % Plotting and telling to hide legend handle
h2 = plot(t, c, 'b', 'DisplayName', 'cosine');  % Plotting and giving legend name
plot(t, m, 'g', 'HandleVisibility','off'); % Plotting and telling to hide legend handle

legend show  % Generating legend based on already submitted values

This give me the same graph as shown in Eitan T’s answer.

It should be noted that this will affect other matlab functions also, for example will cla only remove the plots mentioned on the legend. Search for HandleVisibility in the Matlab documentation for more about that.

Leave a Comment

tech