MATLAB Answers

Programmatically performing "Expand axes to fill figure"?

340 views (last 30 days)
Nancy Jestel
Nancy Jestel on 8 Aug 2017
Commented: andreadr on 29 Jan 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 on 8 Aug 2017
To set the position as tight as possible:
AxesH = axes;
InSet = get(AxesH, 'TightInset');
set(AxesH, 'Position', [InSet(1:2), 1-InSet(1)-InSet(3), 1-InSet(2)-InSet(4)])
andreadr on 29 Jan 2021
to build just a little bit on @Jan's reply, I suggest to repeat two times the commands
InSet = get(AxesH, 'TightInset');
set(AxesH, 'Position', [InSet(1:2), 1-InSet(1)-InSet(3), 1-InSet(2)-InSet(4)])
This is because resizing the plot the first time might induce automatic changes in the text labels (such as for example by adding a final tick label, if the corresponding option is set to 'auto') and update TightInset values.
As a result, some text might be cropped or eccessive margin may be added. Resizing another time uses the updated TightInset and should solve potential issues.

Sign in to comment.

More Answers (2)

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!