Can't get the legend right

Hi
I plotted a few things on the chromaticity diagram below.
h1 to h3 are to plot three black lines, h4 is to plot dataset A, and h5 is to plot dataset B (with psudo code given below).
h1 = plot(line1)
h2 = plot(line2)
h3 = plot(line3)
h4 = plot(dataset A)
h5 = plot(dataset B)
When I put
legend
It shows the legend as below.
But I only need the legend for datasets A and B.
How to use the legend properly in this case?

 Accepted Answer

One way is to pass the graphics objects (i.e., lines, etc.) in as inputs to legend:
figure()
h1 = plot(1:10);
hold on
h2 = plot(2:11);
h3 = plot(3:12);
% legend for h2 and h3 only
legend([h2 h3],{'h2' 'h3'})
Another way would be to set the HandleVisibility of the objects you don't want in the lengend to 'off':
figure()
h1 = plot(1:10,'HandleVisibility','off');
hold on
h2 = plot(2:11);
h3 = plot(3:12);
% no need to supply [h2 h3] as the first argument this time
% (probably still a good idea though)
legend({'h2' 'h3'})

4 Comments

Thank you. That really helped.
In your first method I can modify the line
legend([h2 h3],{'h2' 'h3'})
to
legend([h2 h3],{'A' 'B'})
to however I want to name the dataset.
I am not sure how I can achieve that in your second method.
It's the same. Let me write down the same code as in my answer, but using the names 'A' and 'B':
% Method 1
figure()
h1 = plot(1:10);
hold on
h2 = plot(2:11);
h3 = plot(3:12);
% legend for h2 and h3 only
legend([h2 h3],{'A' 'B'})
% Method 2
figure()
h1 = plot(1:10,'HandleVisibility','off');
hold on
h2 = plot(2:11);
h3 = plot(3:12);
% no need to supply [h2 h3] as the first argument this time
% (probably still a good idea though)
legend({'A' 'B'})
You really only need to use one of the above two methods, of course, and if it were up to me, I would use Method 1.
That's really useful to know. Thank you.
You're welcome!

Sign in to comment.

More Answers (0)

Tags

Asked:

on 7 Dec 2022

Commented:

on 8 Dec 2022

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!