Programmatically performing "Expand axes to fill figure"?

231 views (last 30 days)
Nancy Jestel
Nancy Jestel on 8 Aug 2017
Commented: Joshua on 11 Jun 2021
I need to automate generating figures and exporting them (usually to png). I can get what I need by using "File: Export Settings" & clicking "Expand axes to fill figure", but I really do not want to do this as many times as would be needed. How do I do it from a script or function? I have hunted through all of the properties options that I can think of but can't find that one - or can't get other options to work right. Thank you.

Accepted Answer

Jan
Jan on 8 Aug 2017
To set the position as tight as possible:
figure;
AxesH = axes;
drawnow;
InSet = get(AxesH, 'TightInset');
set(AxesH, 'Position', [InSet(1:2), 1-InSet(1)-InSet(3), 1-InSet(2)-InSet(4)])
  5 Comments
Joshua
Joshua on 11 Jun 2021
This doesn't work for Legends outside the plotting area, e.g. with:
legend('show','Location','Southoutside')
I used the following with good results:
% Create legend and get handle
leg = legend(h,'Location','Southoutside','Orientation','horizontal','NumColumns',10);
LegPos = leg.Position;
% Resize axis
InSet = get(gca, 'TightInset');
set(gca, 'Position', [InSet(1), InSet(2)+LegPos(2), 1-InSet(1)-InSet(3),...
1-InSet(2)-InSet(4)-LegPos(2)]);
It works as long as your Legend does not extend outside of the axes extents horizontally.

Sign in to comment.

More Answers (2)

TastyPastry
TastyPastry on 8 Aug 2017
You can grab the axes handle with something like
h = axes;
Now, when you finish plotting on the axes with the handle h, you can run
set(h,'position',[0 0 1 1])
This will expand your plottable area to fill the figure. However, it may also cut off any title or axis labels you have, so you need to plan accordingly.
Something like
set(h,'position',[.05 .05 .9 .9])
will allow you to see more of the text outside of the plottable area.
Note that you can also use dot operator to set axes properties, but if you're running on older versions of MATLAB you'll need to use the get() and set() functions to modify properties.
  1 Comment
Nancy Jestel
Nancy Jestel on 9 Aug 2017
Thank you for your answer. I have tried to get the position settings to work but I always run into trouble predicting how much to cut off for axis labels and titles since their length changes. I gave up and switched to the interactive tool, but I think Jan's answer below will do the trick.

Sign in to comment.


Salai Selvam V
Salai Selvam V on 19 Jul 2019
Thank, ji. It helped me really great...thanks once again.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!