t = 0 : 0.01 : 2 * pi;
s = sin(t);
c = cos(t);
m = -sin(t);
hold on;
plot(t, s, 'r');
plot(t, c, 'b');
plot(t, m, 'g');
hold off;
legend('', 'cosine', '');
There are several curves in my plotting. I want to display legend for only some of them. How do I do it?
For example, how do I make only the legend for the cosine curve visible in the plotting above? When I call the legend()
functions as legend('', 'cosine');
instead of adding the empty third parameter, indeed the third green line is removed from the legend. But that doesn't solve my problem, because the undesired red line stays visible.
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.