14

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?

Community
  • 1
  • 1
Doresoom
  • 7,398
  • 14
  • 47
  • 61

1 Answers1

8

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

Amro
  • 123,847
  • 25
  • 243
  • 454
  • Yes, I know it's done automatically, but I have three sets of axes stacked vertically which plot separate data sets from a simultaneous aquisition. The labels are date stamps, so I only need one legend. The problem is when I only add the legend to the center plot, the other two don't line up any more. I've got a blank on the end of the GUI with enough room for the legend, and I want to place it there. – Doresoom Aug 30 '10 at 17:18
  • 1
    you can always manually set its `Position` property to fit your layout – Amro Aug 30 '10 at 17:24
  • @Doresoom: I added an example using the idea above. – Amro Aug 30 '10 at 17:37
  • Yeah, I just got this working too - your suggestion of editing the position property got me on the right track. – Doresoom Aug 30 '10 at 17:42
  • this implies that the answer to the original question is "no", right? – craq Nov 24 '14 at 13:29
  • @craq: what do you mean? If you place a legend located "outside", MATLAB will resize the axes to make room for the legend. If you are not happy with the automatic layout, you can do it manually like I showed in the example above. – Amro Nov 24 '14 at 20:07
  • @Amro sorry, I should have looked more closely at your answer. When placing the legend outside the axes it is unavoidable that MATLAB resizes the axes (which is why I thought the answer was no). By placing the legend inside the axes you avoid the automatic resize, and can indeed freely reposition the legend afterwards. I originally read your answer as a manual correction of the automatic resizing of hAx2, which also works, i.e. change the last two lines to this: `h = legend(hAx2, 'sin(x)','location','eastoutside'); set(hAx2,'position',[0.05 0.4 0.7 0.2])` – craq Nov 25 '14 at 09:29