Search code examples
matlabplotmatlab-figurelegendlegend-properties

Matlab legend font size doesn't update when using [l,icons,plots,txt] = legend()


I am having difficult changing the font size used in the legend of a plot in Matlab R2016a. If I use the preferred syntax l = legend() then it works correctly. However, I need access to the icons handle in order to change the facea property. Therefore, I am using the syntax [l,icons,plots,txt] = legend() which according to Matlab "is not recommended and creates a legend that does not support all graphics features." When using this syntax the font size doesn't update correctly. Is there anyway to get the correct font size and transparent legend icons?

%% Some data to plot
x=linspace(1,10);
y=linspace(1,20);
[xx,yy]=meshgrid(x,y);
zz1=2*xx+3*xx.*yy+yy.^2;

%% Correct font, but icons not transparent
figure(1)
h=surf(x,y,zz1,'FaceColor','b','EdgeColor','none');
alpha(h,0.4)
l=legend('plot1');
l.FontSize=24;
l.FontName='Wide Latin';

%% Icons transparent, but incorrect font
figure(2)
h=surf(x,y,zz1,'FaceColor','b','EdgeColor','none');
alpha(h,0.4)
[l,icons,plot,text]=legend('plot1');
l.FontSize=24;
l.FontName='Wide Latin';
set(findobj(icons,'type','patch'),'facea',0.4)

Solution

  • In the multiple output call, it looks like the font size is attached to the second output of Legend. Try this example:

    %Plot some data and a legend
    [X,Y,Z] = peaks;
    surf(X,Y,Z)
    [LEGH,OBJH,OUTH,OUTM] = legend('Peaks legend');
    
    %Change the transparency of the legend patches
    OBJH(2).FaceAlpha = 0.4;  %Your "findobj" call is probably more reliable.
    
    %Change the fontsize
    OBJH(1).FontSize = 6;   %Your "findobj" call is probably more reliable.
    
    %If you change the "fontsize" of the main legend object, 
    %    that seems to change the size of the legend box, but not the contents.
    LEGH.FontSize = 16;
    %This could actually be useful, for example to fine tune the size 
    %    of the box. But it is pretty counterintuitive.
    

    To be diretly applicable to your code:

    %% Altogether now
    figure(3)
    h=surf(x,y,zz1,'FaceColor','b','EdgeColor','none');
    alpha(h,0.4)
    [l,icons,plot,text]=legend('plot1');
    %Set the objects that you want
    set(findobj(icons,'type','Text'),'FontSize',24)
    set(findobj(icons,'type','Text'),'FontName','Wide Latin')
    set(findobj(icons,'type','patch'),'facea',0.4)
    
    %Make painful adjustments to item positioning (there should be a better way ...)
    l.FontName='Wide Latin';  %These two lines get the box about the right size
    l.FontSize=24;
    icons(2).Vertices([3 4],1) = 0.2; %This squeezes the color patch to the left
    icons(1).Position(1) = 0.3;       %This moves the text to the left to fit in the box
    

    (I'm currently running R2015a. This fine detailed behavior may change slightly in your more updated version.)