How do I skip items in legend? Say I have 6 plots with 3 actual values and 3 interpolated curves. I only want to label the actual value curves so
legend('first','','second','','third')
doesn't really work because the interpolated curve still shows.

14 Kommentare

EhsanZ
EhsanZ am 12 Mär. 2018
1- Select the curve you don't want have legend. 2- Go to the "more properties" (while the curve is still selected). 3- Turn "HandleVisibility" off.
FTil
FTil am 16 Jun. 2018
Or programmatically:
plot(...,'HandleVisibility','off')
figure
h1=histfit(no_ess,20,'gamma');
xlim([0 1])
hold on
h2=histfit(with_ess,50,'kernel');
xlim([0 1])
set(get(get(h1(2),'Annotation'),'LegendInformation'),'IconDisplayStyle','off');
set(get(get(h2(2),'Annotation'),'LegendInformation'),'IconDisplayStyle','off');
legend('MCR SOL','MCR SOL ESS')
Here's a quick sample of how it worked- for my histograms I didn't want the two red lines to be labelled in the legend. I found out that for the histograms- it creates a handle h(1) and (2) where 1 corresponds to the bar charts and 2 to the fitting lines.
Just an example- hope it helps!
sample.PNG
neurosock hardcore BCIs
neurosock hardcore BCIs am 27 Jan. 2021
Bearbeitet: neurosock hardcore BCIs am 27 Jan. 2021
The nice thing about 'HandleVisibility' in contrast to 'IconDisplayStyle' is that it can be called directly in the function of plots and patches:
plot(...,'HandleVisibility','off')
patch(...,'HandleVisibility','off')
Dandro18048
Dandro18048 am 6 Apr. 2021
@FTil I was looking exactly for this, thank you very much! Simplest solution of everything that's been posted here.
Giuseppe Degan Di Dieco
Giuseppe Degan Di Dieco am 15 Jun. 2021
Dear Akash,
thanks for your tip, hope you're still reagind these days.
It really helped me in avoid plotting one of two labels in a stacked bar plot.
Best.
Rik
Rik am 15 Jun. 2021
@Giuseppe Degan Di Dieco, regarding your flag ("Really helpful, and easy to code because of the set and get commands!"): flags are used to attract the attention of site admins and users with editing privileges. They should not be used as personal bookmarks.
Giuseppe Degan Di Dieco
Giuseppe Degan Di Dieco am 16 Jun. 2021
Sorry then, if there is a way for removing it, please let me know, and I will amend it.
I will bear in mind for the future.
Best.
Rik
Rik am 16 Jun. 2021
No problem. I have already removed the flag.
Giuseppe Degan Di Dieco
Giuseppe Degan Di Dieco am 29 Jul. 2021
Hi Rik,
thanks for your work.
Best.
Hello,
the changes made in MATLAB 2021a do not produced expected/desired results. Using
leg = legend('first','second','third')
leg.String(2) = ''
does not skip producing a legend label for the second curve but rather assigns the label 'third' to the second curve.
I couldn't find any hint in the documentation how to actually skip/remove legend labels for particular curves and keep the others as is.
Ok this workaround found in the comments below, actually solved my problem:
legend([h1 h3],{'Leg1' 'Leg3'});
Assuming that the line1 and line3 have been assigned to h1 and h3 (h1 = plot(...), h3 = plot(...)), respectively.
Greg Vieira
Greg Vieira am 4 Sep. 2021
How can you do this for multiple plots? For example, I have 1001 data sets plotted and only want the legend to show 1 of the first 1000 plots and the last plot. It is not reasonable for me to place 999 ' ' placeholders.
Kaveh Vejdani
Kaveh Vejdani am 10 Jun. 2023
First plot data1, then data1001, the set L.AutoUpdate = 'off'; % L=Legend

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Kenneth Eaton
Kenneth Eaton am 29 Aug. 2023
Bearbeitet: MathWorks Support Team am 10 Jan. 2022

109 Stimmen

Starting in R2021a, you can leave an item out of a legend by setting the corresponding label to an empty character vector. For example, plot three lines. Then call the legend function and specify the second legend label as an empty character vector. The corresponding line is omitted from the legend.
plot(rand(3)); legend('Line 1','','Line 3')
Note that this strategy works when you specify just the labels, and not when you specify a set of objects to include in the legend.
For previous releases, you can specify the objects that you want to include as the first input argument to the “legend” function.  
For example, plot three lines and return the “Line” objects as array “p”. Include only the first and third lines in the legend by specifying “p(1)” and “p(3)” as the first input argument to “legend”. 
 p = plot(rand(3)); 
 legend([p(1) p(3)],'plot 1','plot 3') 
Alternatively, you can set the “IconDisplayStyle” to “off” for the object that you do not want to include in the legend. For example, exclude the second “Line” object, “p(2)”. 
 p = plot(rand(3)); 
 set(get(get(p(2),'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 
 legend('plot 1','plot 3') 

10 Kommentare

Dan
Dan am 17 Jan. 2017
If the lines were created in a seperate file and you can't reach them :
h = findobj(gca,'Type','line');
will get you all of the line objects :)
Walter Roberson
Walter Roberson am 17 Jan. 2017
Dan, in terms of the original Question, that would get you the handles of the "actual" lines together with the "interpolated" lines. Potentially you might know which is which by indexing; otherwise you might need to examine the line properties such as the linestyle in order to figure out whether it is one of the ones you want or not.
Zheng Liu
Zheng Liu am 10 Jan. 2018
Bearbeitet: Zheng Liu am 10 Jan. 2018
Hi Ken, I found the solution works most cases, except I have an unexist line (which has an empty handle). I want to skip the legend of the line, if the line not there. For example:
h1 = plot([]); % Blue line
hold on;
h2 = plot(rand(1,10),'r'); % Red line
h3 = plot(rand(1,10),'g'); % Green line
legend([h1 h2 h3],{'want to skip this if line unexist', 'hello', 'world'});
However, the legend for h1 will be assigned on h2, and the legend for h3 will be ignored. Do you have any idea of this? Thanks!
For anyone using this technique, be advised it seems that legend('Location','SouthEast') resets the plot to give the full set of legends, even those dropped (at least in 2016b). For example,
legend([h1 h2],{'Leg1' 'Leg2'});
legend('Location','SouthEast'); % this sequence shows all legends, not just 1st two.
legend('Location','SouthEast'); % this sequence shows just the first 2 legends
legend([h1 h2],{'Leg1' 'Leg2'});
Not sure if this is a bug or a feature. :)
Tomer Nahshon
Tomer Nahshon am 24 Mär. 2021
@Zheng Liu Wonderful answer,
Thank you!
Dan Houck
Dan Houck am 22 Dez. 2021
I just upgraded from 2020a to 2021b. Previously, using an emptry character vector in the legend would leave the symbol (line, marker, etc.) and just not give it a label. Now that omits the entire legend entry. How do I get the former again???
Can you just use a space instead?
plot(rand(3));
legend('Line 1',' ','Line 3')
Sheridan McPheeters
Sheridan McPheeters am 18 Okt. 2022
@DGM your solution leaves the item in the legend, only unlabeled. This is a poor solution if you have many items which you do not want to appearin the legend, such as knots in a spline, local minima and maxima, etc. Also, in 2021a and on, I believe, using empty quotes (i.e. ''), rather than a space, will remove the item from the legend, entirely.
DGM
DGM am 18 Okt. 2022
Bearbeitet: DGM am 18 Okt. 2022
I was responding to @Dan Houck who was asking specifically for a means to avoid the implicit item removal that happens in R2021a. Leaving the unlabeled marker was the goal.
As to whether what Dan asked for is visually objectionable, you're free to tell him.
Kaveh Vejdani
Kaveh Vejdani am 10 Jun. 2023
L = legend;
L.AutoUpdate = 'off';

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (13)

Matt Lobo
Matt Lobo am 1 Nov. 2021
Bearbeitet: Matt Lobo am 30 Nov. 2021

66 Stimmen

Essentially set the 'HandleVisibility' attribute to 'off' when plotting something, as such:
plot(x,y,'HandleVisibility','off')
This has some implications concerning interacting with that handle in other ways, but if you don't plan on using the handle, this is a great dynamic way to not include certain plots in your legend. It works especially well when you're plotting iteratively, and don't want to store handles and then hard-code the legend to fit your exact plot.

5 Kommentare

Giuseppe Degan Di Dieco
Giuseppe Degan Di Dieco am 2 Nov. 2021
Thank you Matt for updating the thread.
Keep in touch for tips sharing and creating a MATLAB users community.
Best.
Michael Van de Graaff
Michael Van de Graaff am 17 Jan. 2022
This was very helpful Matt, thank you
Sebastian Lopez
Sebastian Lopez am 27 Mai 2022
Really helpful. Thanks!
Really helpful. Thanks!
Hannah
Hannah am 25 Sep. 2024
Fantastic advice. Thank you.

Melden Sie sich an, um zu kommentieren.

Walter Roberson
Walter Roberson am 25 Jan. 2011
Bearbeitet: Rik am 5 Apr. 2022

27 Stimmen

You can set the IconDisplayStyle to off for the items you do not wish a legend for. See this documentation.
Edit by @Rik (2022/04/05):
The link above was valid for the documentation from R2012a. The equivalent page in R2022a suggests a different strategy (i.e. only providing the handles to legend for the objects you wish to include). In the current release IconDisplayStyle is documentated under the properties of the graphics primitives (e.g. line objects or patch objects).
Documentation pages from specific releases will remain online for 5 years.

6 Kommentare

Jack Barrett
Jack Barrett am 27 Okt. 2011
this is a much nicer solution. kudos
Wow, this solution is much smoother than the other proposed, and more generally applicable.
It allows you to turn off the ones you don't want, rather than having to turn on the ones you do. If you (like me) are plotting many data sets on the same graph, this is much more useful and simple.
If you have the handle for the data set you DON'T want included, all you need is this line:
set(get(get(h,'Annotation'),'LegendInformation'),'IconDisplayStyle','off');
where "h" is changed to the name of your handle.
For more information, follow the link provided by Walter and John.
Tom
Tom am 22 Apr. 2016
This is the ideal solution for implementing "plot" in a loop where it is difficult to assign a unique handle each iteration. Thank you!
Nuwan Liyanage
Nuwan Liyanage am 25 Aug. 2020
This is really helpful, thanks!
Fernando Zigunov
Fernando Zigunov am 29 Nov. 2021
broken link!
Tanya Meyer
Tanya Meyer am 5 Apr. 2022
Yes - broken link :(

Melden Sie sich an, um zu kommentieren.

Junette Hsin
Junette Hsin am 21 Mär. 2019
Bearbeitet: Junette Hsin am 21 Mär. 2019

25 Stimmen

I ran into this problem and I have not seen this method suggested yet, but I solved it by changing the order of my plotted lines which affects what the legend displays (I am using MATLAB R2017b).
Let's say you plot 2 lines first, and then create a legend. Then you plot a 3rd line. That 3rd line will be added to your legend as 'data 1'.
Instead plot 3 lines, and then in your legend, label just the first 2 lines. The 3rd line will be omitted from the legend.
Hope this helps.

5 Kommentare

TheLast One
TheLast One am 1 Jun. 2019
Simplest solution :)
Orhan Soyuhos
Orhan Soyuhos am 13 Jun. 2020
Thank you!
Jim Tonti
Jim Tonti am 17 Apr. 2021
Bearbeitet: Jim Tonti am 22 Jun. 2021
Another way to eliminate further plots from getting an automatic legend update (resuting in the 'data 1', 'data 2' etc. legend entries) was suggested by Phuc Bui on 2021-03-03 in a comment for the entry zoomPlot : Kelsey Bower (2021). zoomPlot
The most simple way to avoid "data1", "data2" is turning off the autoupdate property of the legend:
legend({'A','B'},'AutoUpdate','off')
Brent F
Brent F am 22 Jun. 2021
Bearbeitet: Brent F am 10 Aug. 2021
@Jim Tonti Yes! Upvote his solution: legend({'A','B'},'AutoUpdate','off')
Gabriela Belicova
Gabriela Belicova am 13 Mai 2022
Both very helpful, thank you so much !!!

Melden Sie sich an, um zu kommentieren.

Yasin Zamani
Yasin Zamani am 25 Sep. 2019
Bearbeitet: Yasin Zamani am 25 Sep. 2019

21 Stimmen

For example, suppose you want to skip the name of the first plot in the legend:
x = linspace(0, 2 * pi);
% sin(x)
h = plot(x, sin(x));
% the following line skip the name of the previous plot from the legend
h.Annotation.LegendInformation.IconDisplayStyle = 'off';
% cos(x)
plot(x, cos(x));
% legend
legend('cos');

4 Kommentare

Giulio Suzumura
Giulio Suzumura am 17 Okt. 2020
Tks. Best approach when uses 'hold on's and external functions.
Donald Liu
Donald Liu am 21 Jul. 2021
Good solution, short and concise!
Carl Witthoft
Carl Witthoft am 8 Sep. 2021
doesn't seem to work for a "fill" object
Soham Sinha
Soham Sinha am 11 Mai 2022
Thanks

Melden Sie sich an, um zu kommentieren.

Boris Blagojevic
Boris Blagojevic am 23 Jun. 2021

18 Stimmen

An alternative approach: Prevent the legend from updating
First, plot the lines that you want to have labeled. Then, specify the legend and set
legend(....,'AutoUpdate','off')
then, plot the remaining lines

4 Kommentare

Riaan Ferreira
Riaan Ferreira am 10 Aug. 2021
This worked briliantly
Faezeh Ashouri
Faezeh Ashouri am 10 Apr. 2022
Thanks!
Rik
Rik am 13 Jun. 2022
Comment posted as flag by Fatima u'wais:
intersted
Dr.Jaber Aljuaidiyah
Dr.Jaber Aljuaidiyah am 20 Aug. 2024
This works nicely. Thanks pal

Melden Sie sich an, um zu kommentieren.

the cyclist
the cyclist am 25 Jan. 2011

8 Stimmen

Each curve has a handle, which can be obtained from the properties. Use the form of legend that takes two arguments (handle and legend), and only use the handles of those curves that you want to show.
Dilshad Raihan
Dilshad Raihan am 26 Okt. 2015
Bearbeitet: Dilshad Raihan am 26 Okt. 2015

2 Stimmen

You can do this by first plotting the curves in an order so that the lines you don't want to be displayed in the legend comes in the end. That is, suppose you have N lines to be plotted but you dont want to display m of these in the legend. Then first plot the required N-m lines and then the remaining m. After that, turn the legend on, click on the legend and the "legend property editor" will be displayed. Go to the "more properties" option. You can see an entry titled "String" specified as a "1xN cell array". Click on the cell array icon and set the size as "1xN-m". Now, only the first N-m curves will be displayed in Legend.
Diaa
Diaa am 17 Nov. 2020
Bearbeitet: Diaa am 17 Nov. 2020

1 Stimme

You can simply delete the last undesired entry by the following:
% assume you plotted some curves before this line and all of them are desired to be shown in the legend
hleg = legend('show');
plot(x,y) % you don't need this plot in the legend
hleg.String(end) = []; % delete the last legend entry of the very last plot
% continue plotting while copy and paste the previous line immediately after any plot you don't need in the legend

1 Kommentar

Amir Semnani
Amir Semnani am 9 Jun. 2021
Thanks. That worked for me (MATLAB 2017b) and it's very simple. Let's assume we have 8 datasets and we want to plot all of them, but only want to see the legend for dataset with even number.
x=ones(100,1)*(1:8); plot(x);ylim([0 9]); hleg = legend ('show'); hleg.String(1:2:end)=[];

Melden Sie sich an, um zu kommentieren.

Image Analyst
Image Analyst am 25 Sep. 2024

1 Stimme

Every time you plot, get the handle to the points or curves. Then pass only those that you want into legend. Here is a full demo:
lineSize = 2;
markerSize = 30;
% Define 3 data sets
x1 = [-1.9, 0.004, 1.94];
x2 = [-1.94, -0.23, 1.95];
x3 = [-1.92, .2, 1.93];
y1 = [13.885, 10.168, 14.235];
y2 = [9.3805, 5.2697, 9.3367];
y3 = [4.5262, 0.80904, 4.0889];
% Interpolate the 3 curves.
xFit = linspace(-2, 2, 500);
coefficients1 = polyfit(x1, y1, 2);
yFit1 = polyval(coefficients1, xFit);
coefficients2 = polyfit(x2, y2, 2);
yFit2 = polyval(coefficients2, xFit);
coefficients3 = polyfit(x3, y3, 2);
yFit3 = polyval(coefficients3, xFit);
% Plot the 3 data sets and their interpolated curves
handle1 = plot(x1, y1, 'r.', 'MarkerSize', markerSize);
hold on;
handle2 = plot(xFit, yFit1, 'r-', 'LineWidth', lineSize);
handle3 = plot(x2, y2, 'b.', 'MarkerSize', markerSize);
handle4 = plot(xFit, yFit2, 'b-', 'LineWidth', lineSize);
handle5 = plot(x3, y3, 'g.', 'MarkerSize', markerSize);
handle6 = plot(xFit, yFit3, 'g-', 'LineWidth', lineSize);
grid on;
% Have the legend only for the data, not the interpolated fit
% by passing in only the plot handles of the data.
legend([handle1, handle3, handle5], 'Data1', 'Data2', 'Data3', 'Location', 'north');

1 Kommentar

Allyce
Allyce am 20 Aug. 2025
This was certainly an easy way to solve the issue - I was using two y-axis situation and had optional items in each axis - so I COULD have ordered the plot statements but much easier to set up the handles and then use the legend at the end. Thank you.

Melden Sie sich an, um zu kommentieren.

Akshay Ravindran
Akshay Ravindran am 26 Nov. 2015

0 Stimmen

Why is it that this error keeps coming up?
<<
>>

3 Kommentare

Walter Roberson
Walter Roberson am 26 Nov. 2015
[z, x, c, v, b, n, m] looks like it might be intended as the list of "entries" to be annotated. Is it possible that those variables all hold column vectors instead of scalars, with the result that [z, x, c, v, b, n, m] is a 2 dimensional array?
Ajith Tom George
Ajith Tom George am 17 Nov. 2016
If z,x,c etc are the handles, then remove the commas:
i.e. [z w c ...] and you are good to go!
No, in each case where z w c etc are expressions that have no spaces in them, [z w c ...] is the same as [z, w, c, ...]
Spaces in expressions sometimes trigger parsing as if there were multiple expressions. For example:
[1 -2*x]
is considered two expressions, 1 and -2*x

Melden Sie sich an, um zu kommentieren.

Luke Marsden
Luke Marsden am 2 Feb. 2017

0 Stimmen

I am trying to do a similar thing using this line of code:
leg = legend([p4 RETU_Average activity1 Vulcanian1], 'Tilt', 'RETU Mean Amplitude', 'Activity', '"Vulcanian" Explosions', 'Location', 'northeast');
I am getting this error:
Error using matlab.graphics.chart.primitive.Line/horzcat
Cannot convert double value 23 to a handle
Error in p1_zoom_plot (line 93)
leg = legend([p4 RETU_Average, activity1 Vulcanian1], 'Tilt', 'RETU Mean Amplitude', 'Activity', '"Vulcanian" Explosions', 'Location', 'northeast');

4 Kommentare

Walter Roberson
Walter Roberson am 2 Feb. 2017
One of p4 RETU_Average activity1 Vulcanian1 contains the numeric value 23 instead of containing the handle to a graphics object.
The comma looks suspicious there.
I speculate that you might have passed in the values you are plotting rather than a copy of the handle that you got when you plotted them.
Thanks for your reply Walter. With your help I have solved the problem.
23 is the first value in the vector named 'RETU_Average'. I was trying to pass the vector into the legend rather than the handle, which I created using this line of code.
p1 = plot (time, RETU_Average, 'LineWidth', 2);
New legend text for reference of anyone else who has made a similar mistake:
leg = legend([p4 p1 activity1 Vulcanian1], 'Tilt', 'RETU Mean Amplitude', 'Activity', '"Vulcanian" Explosions', 'Location', 'northeast');
Brent F
Brent F am 10 Aug. 2021
Have you gotten this method of generating a legend using plot handles to work within a subplot?
Rik
Rik am 11 Aug. 2021
@Brent F A subplot is simply a new axes object, so any method should work. You should be careful when using gca or when not supplying a handle at all, as the last axes with user interaction will be the target of your calls.

Melden Sie sich an, um zu kommentieren.

Juan Carlos de Luna
Juan Carlos de Luna am 6 Apr. 2020

0 Stimmen

Select line in Plot Browser and type
set(get(get(gco,'Annotation'),'LegendInformation'),'IconDisplayStyle','off')

2 Kommentare

Bart Boonstra
Bart Boonstra am 12 Apr. 2021
Thanks that worked for me!
Marya Sadki
Marya Sadki am 29 Nov. 2021
Me too thanks

Melden Sie sich an, um zu kommentieren.

K Anderson
K Anderson am 30 Aug. 2024

0 Stimmen

If you plot multiple lines with the same plot command like this
h(1,:) = plot(rand(4,11),'r')
h =
1x11 Line array: Line Line Line Line Line Line Line Line Line Line Line
hold on
h(2,:) = plot(rand(4,11),'b')
h =
2x11 Line array: Line Line Line Line Line Line Line Line Line Line Line Line Line Line Line Line Line Line Line Line Line Line
and use
legend
on this, you get a 2x11 long legend
but you only want to highlight the first red and first blue line use this;
legend([h(1,1) h(2,1)],'red','blue')
This is mentioned in the documentation as;
legend(subset,___) only includes items in the legend for the data series listed in subset. Specify subset as a vector of graphics objects. You can specify subset before specifying the labels or with no other input arguments.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by