Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide MATLAB legend entries for some graphical objects in plots

MATLAB legends list everything in a plot, including guidelines that you have put on a plot.

A fudge to get around that is to do

*Plot
*Add legend
*Add guidelines

However, MATLAB puts the most recent lines in the front, meaning the guidelines then sit over the displayed data; ugly and distracting.

Similar problems occur any time you build up a complicated plot, legend freaks out and grabs everything, and workarounds with plotting order can be ugly

Example code:

%**** Optional guidelines
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;
  %* Plot
  figure(1)
  plot(x,y(plotLoop,:));
  hold on
end

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

(move the code block order to replicate the situations mentioned above)

How to reasonably fix this?

like image 589
Mark_Anderson Avatar asked Jan 05 '23 11:01

Mark_Anderson


1 Answers

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
like image 128
Jonas Avatar answered Jan 15 '23 07:01

Jonas