Remove data elements of the legend from figure
    290 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    Marisabel Gonzalez
 el 9 de Abr. de 2019
  
    
    
    
    
    Comentada: Jaime Abad Arredondo
      
 el 2 de Oct. de 2025 a las 16:36
            Hi,
I have several figures in a loop-rich script in which the information of the legend would vary for most of the figures. I was wondering if there is a way of removing data elements from the legend using figure setting options. I know I can insert/remove the legent, rename the data points, change the legend appearance, etc, but I am not sure if I can remove elements from it. 
For example, in the figure below I would've like to remove the last column but not by using code, instead doing it from the figure itself.
I am aware my changes won't be saved. 

0 comentarios
Respuesta aceptada
  Kelly Kearney
      
 el 9 de Abr. de 2019
        Technically, you can delete parts of a legend, but I only know how to do it via code, not via to UI.  
I should mention that using the multiple-output syntax for legend is "not recommended" by the official documentation, meaning this code could easily break in future versions of Matlab... but they've been saying that since the HG2 release in 2014b and so far I've only encountered problems in a few edge cases.
Anyway, if you really want to delete parts of a legend, here's how you can:
% An example plot, 10 to-be-labeled lines and 3 extras
h1 = plot(rand(10,9), 'ro');
hold on
h2 = plot(rand(10,3), '-k');
lbl = strtrim(cellstr(num2str((1:12)', 'data%d')));
% Label everything
[hleg, hico] = legend(lbl);
% Delete objects associated with last 3 black lines
istxt = strcmp(get(hico, 'type'), 'text');
hicot = hico(istxt);
hicol = hico(~istxt);
delete(hicot(ismember(get(hicot, 'String'), {'data10','data11','data12'})));
delete(hicol(ismember(get(hicol, 'Tag'),    {'data10','data11','data12'})));
The better solution would be to just not label those lines at all from the start:
% An example plot, 10 to-be-labeled lines and 3 extras
h1 = plot(rand(10,9), 'ro');
hold on
h2 = plot(rand(10,3), '-k');
lbl = strtrim(cellstr(num2str((1:12)', 'data%d')));
% Label only the desired lines
legend(h1, lbl(1:9))
2 comentarios
  Afiq Azaibi
    
 el 7 de Oct. de 2024
				Starting in R2024b, calling legend with multiple outputs will throw a warning. It will continue to function as it has previously. 
Más respuestas (5)
  EL ISMAILI Mohammed
      
 el 25 de Abr. de 2020
        Hi!
For removing a legend element dirctly from the figure :
-Right click on the legend
-Open "Proprety Inspector"
-Go to: LABELS > Strings. Double clicks on the  string's box
-Remove/Edit what you want 
It works for me. I have the matlab version 2019a.
2 comentarios
  James Ratti
 el 25 de Mzo. de 2021
				When I try this, it deletes the legend name, but not the associated color/symbol key for the entries. So if I have 7 entries and want to hide the names/keys for the first 4 of them by modifying the strings, the other 3 just move to the top of the list and become disconnected from the color/symbol keys they're supposed to represent. I can't find a way around this without the command line. 
  Narges Raee
 el 26 de Oct. de 2022
				same problem as James! it is deleted the names of the objects and shift eveything else up, so not working! 
  Adam Danz
    
      
 el 9 de Abr. de 2019
        
      Editada: Adam Danz
    
      
 el 9 de Abr. de 2019
  
      " I was wondering if there is a way of removing data elements from the figure itself"
If you want to remove objects from a figure that has already been produced, just click on the object and press delete. That will also remove its representation in the legend.  
Another option is to selection objects by using the display name in the legend.  For example, these lines below will find the handle(s) to the object(s) associated with the legend name "data1" and will delete all of those objects. 
allChildren = get(gca, 'Children');                % list of all objects on axes
displayNames = get(allChildren, 'DisplayName');    % list of all legend display names
% Remove object associated with "data1" in legend
delete(allChildren(strcmp(displayNames, 'data1')))
If you want to keep the object on the figure but want to remove its representation from the legend, the only way I know of doing that is to recreate the legend using the object handles to specify legend components.  We can get the text in the legend and delete or edit that but we do not have access to the handles of the legend components.  Most of the time, the figure can be recreated and that's the much easier approach. But if you've got a figure and no code to reporduce it, you'll have to obtain the handles of all graphic objects and then recreate the legend. 
5 comentarios
  Adam Danz
    
      
 el 9 de Abr. de 2019
				
      Editada: Adam Danz
    
      
 el 9 de Abr. de 2019
  
			There is no simple way of removing components of a legend from the figure without the code that produced the figure.  You can rename them, but removing them isn't possible (without the changing the code and reproducing the figure).   
If you have the code that generated the figure, you can edit it so that the legend appears the way you want it to -- that is much simpler.  
There's probably a very complicated and error-prone way of getting all axis object handles and associating then trying to associate them with the legend text in order to re-create the legend but if the legend strings were added with calling legend instead of using 'DisplayNames', then this probably wouldn't work either. 
  Payam Razavi
 el 24 de Feb. de 2023
				% Thanks for this comment, it was really helpful
% If axes cannot be deleted (invisible axes) use:
legend(app.UIAxes,allChildren(~strcmp(displayNames, '')),'location','Best')
  HiWave
 el 31 de Mayo de 2023
        
      Editada: HiWave
 el 31 de Mayo de 2023
  
      Although an answer has been accepted, I'm going to add to the discussion. I too faced a similar circumstance. I found the easiest method was to select the data I wanted to keep, then cut. Delete all the rest of the data and legend, then paste the data back into the plot. Add a new legend and rename the entries. Not exactly efficient, but got the job done. No code necessary.
2 comentarios
  HiWave
 el 31 de Mayo de 2023
				FYI, if you want to then append extra data, without it appearing in the legend, you can turn off "auto update" in the properties.
  Kaveh Vejdani
      
 el 10 de Jun. de 2023
				Thank you HiWave! You're right, the ultimate answer is :
L.AutoUpdate = 'off'; 
Saves the day!
  Michael
 el 27 de Nov. de 2024
        Hi, for me it works setting the property 'HandleVisibility' in the plot command.
In this case the line in the plot is visible, but the entry in the legend is invisible.
plot((Val(:,1)), Val(:,2),'HandleVisibility','off');
3 comentarios
  Jaime Abad Arredondo
      
 el 2 de Oct. de 2025 a las 16:36
				Using matlab 2025a this doesn't work for me anymore... This seems to be a bug in the new version:
M=peaks(50);
hold on 
surf(M,'HandleVisibility','off');
shading interp
colorbar
contour3(M,[0,0],'w--','DisplayName','Foo data contour')
legend('Location','best')
Note that it does remove the entry from the legend, but now the shading command doesn't work 
  Peter Beringer
 el 24 de Ag. de 2021
        There's a very simple way if you're happy to do it in the Figure window itself (you can also go File > Generate Code if you wish to include the settings in the code directly). You're correct that editing the text string in the Properties Inspector is going to leave the unwanted data in the legend, just without a name. Easiest way to do it from within the figure is to go to the top of the Property Inspector window, click the ">" arrow next to "Figure" to open up a drop-down menu, then Apple/command-click or right-click the data you don't want and select "DELETE". See attached screenshot (obviously yours will have different labels, etc.) Hope I've explained that okay. 
Happy MATLABBING! :)

1 comentario
  SIMONE GRANDINETTI
 el 29 de Nov. de 2022
				I tried this but it deletes the data from the plot as well (i was trying to plot a yline alongside a set of curves but i didn't want it to appear in the legend).
Ver también
Categorías
				Más información sobre Legend en Help Center y File Exchange.
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!















