Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
788 views
in Technique[技术] by (71.8m points)

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

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', '');

The Plotting

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...