MATLAB Answers

decrease the vertical space between the subplots

6 views (last 30 days)
Zahra Sheikhbahaee
Zahra Sheikhbahaee on 15 Feb 2021
Answered: Matt J on 15 Feb 2021
I am using this function. How can I decrease the vertical space between the subplots in my figure using this code? I would like to increase slightly the space on the right side of plots because I set some ticks for one of the subplots on the right hand side of the subplot and it has no margin to right
function saveTightFigure(h,outfilename)
if nargin==1
hfig = gcf;
outfilename = h;
hfig = h;
%% find all the axes in the figure
hax = findall(hfig, 'type', 'axes');
%% compute the tighest box that includes all axes
tighest_box = [Inf Inf -Inf -Inf]; % left bottom right top
for i=1:length(hax)
set(hax(i), 'units', 'centimeters');
p = get(hax(i), 'position');
ti = get(hax(i), 'tightinset');
% get position as left, bottom, right, top
p = [p(1) p(2) p(1)+p(3) p(2)+p(4)] + ti.*[-1 -1 1 1];
tighest_box(1) = min(tighest_box(1), p(1));
tighest_box(2) = min(tighest_box(2), p(2));
tighest_box(3) = max(tighest_box(3), p(3));
tighest_box(4) = max(tighest_box(4), p(4));
%% move all axes to left-bottom
for i=1:length(hax)
if strcmp(get(hax(i),'tag'),'legend')
p = get(hax(i), 'position');
set(hax(i), 'position', [p(1)-tighest_box(1) p(2)-tighest_box(2) p(3) p(4)]);
%% resize figure to fit tightly
set(hfig, 'units', 'centimeters');
p = get(hfig, 'position');
width = tighest_box(3)-tighest_box(1);
height = tighest_box(4)-tighest_box(2);
set(hfig, 'position', [p(1) p(2) width height]);
%% set papersize
set(hfig,'PaperSize', [width height]);
set(hfig,'PaperPositionMode', 'manual');
set(hfig,'PaperPosition',[0 0 width height]);
%% save

Answers (1)

Matt J
Matt J on 15 Feb 2021
Instead of subplot(), use subaxis() from the File Exchange.

Community Treasure Hunt

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

Start Hunting!