Add legend outside of axes without rescaling in MATLAB

36,110

EDIT

%# create three axes with custom position
x=0:.1:10;
y=sin(x);
hAx1 = axes('Position',[0.05 0.05 0.7 0.2]); plot(hAx1, x,y)
hAx2 = axes('Position',[0.05 0.4 0.7 0.2]); plot(hAx2, x,y)
hAx3 = axes('Position',[0.05 0.75 0.7 0.2]); plot(hAx3, x,y)

%# add legend to middle one
h = legend(hAx2, 'sin(x)'); pos = get(h,'position');
set(h, 'position',[0.8 0.5 pos(3:4)])

alt text

Share:
36,110
Doresoom
Author by

Doresoom

Mechanical Engineer from St Louis, MO. Former NASA flight controller for the International Space Station.

Updated on August 31, 2020

Comments

  • Doresoom
    Doresoom over 3 years

    I've got a GUI in MATLAB with a set of axes pre-placed. I'm using the location property of the legend to place it to the right hand side of the axes. However, by doing this the axes get re-scaled so that the axes+legend take up the original width of the axes. Is there any way to circumvent the re-size?

    Example:

    x=0:.1:10;
    y=sin(x);
    figure
    pos=get(gca,'position');
    pos(3)=.5; %#re-size axes to leave room for legend
    set(gca,'position',pos)
    plot(x,y)
    

    So far I get:

    alt text

    Place legend:

    legend('sin(x)','location','eastoutside')
    

    ...aaaaand...

    alt text

    MATLAB squishes it all into the original axes space. Any way around this?