Hide MATLAB legend entries for some graphical objects in plots

两盒软妹~` 提交于 2019-12-05 16:35:12

If you want a certain graphics object to not produce a legend (and that will work even if you toggle the legend off and on again), you can modify the LegendInformation:

%# plot something that shouldn't show up as legend
handleWithoutLegend = plot(something);

%# modify the LegendInformation of the Annotation-Property of the graphical object
set(get(get(handleWithoutLegend,'Annotation'),'LegendInformation'),...
    'IconDisplayStyle','off');

%# toggle legend on and off at will, and never see the something-object appear

If you try to turn off the legend on an array of handles, the best way is just to loop over them, with a try-wrapper for graphical objects that cannot produce a legend:

for h = listOfHandles(:)'
   try
      set(get(get(h,'Annotation'),'LegendInformation'),...
        'IconDisplayStyle','off');
   end
end

Craft a custom handle that you feed into the legend. Plot handles can be concatenated to form an object that legend is happy to accept as input.

The required code isn't pretty, but it does work.

%**** Optional guidelines for periodicity
figure(1)
plot([2 2],[0,1],'k--'); hold on

%**** DATA
N = 4;
y=rand(5,N);
x=1:1:5;

for plotLoop=1:N;
  LegTxt{plotLoop} = num2str(plotLoop);
  %* Plot
  figure(1)

  % if statement to construct a handle for the legend later
  if plotLoop==1 
      htot=plot(x,y(plotLoop,:));
  else
      h=plot(x,y(plotLoop,:));
      % Append this info to the figure handle
      htot= [htot, h];
  end
  hold on

end

%*****LEGEND
hLegend = legend(htot,LegTxt,...
                'interpreter','latex','FontSize',16,...
                'location','eastoutside')

For the pedantic or curious, the loop for plotLoop=1:N; is here because I extracted the example from some rather complex code where the data is extracted from cell arrays. Obviously you could eliminate that loop for a lot of usage scenarios, I just decided to keep the code in its most flexible format!

You can also hide plot from legend in another way. Here's the sample:

figure(1)
hold on

x=1:10;
y1=x;
y2=x.^2/10;
y3=x.^3/100;

plot(x,y1);
plot(x,y2,'HandleVisibility','off');
plot(x,y3);

legend('x','x^3')

You just need to put 'HandleVisibility', 'off' to your plot that you don't want to show up in legend. That's how result looks like:

HandleVisibility is a line property so it might now work if you create plot in some other way. But for most use cases its enough and it is much simpler.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!