# Customize the spacing of subplots2

Posted by Brett Shoelson,

Brett's Pick this week is the Tight Subplot, by Pekka Kumpulainen.

Judging from the title of the submission, Pekka wrote and shared "Tight Subplot" because he was dissatisfied with the large (default) gaps between axes generated with the subplot command. Fair enough (though with a bit of effort, one can customize the position of subplots). But what I really like about "Tight Subplot" is not that the default axes spacing makes better use of the figure's real estate, but that it gives me complete--and easy--control over horizontal and vertical gap spacing, and separately, of left-and-right and top-and-bottom margin spacing. The syntax is easy to use:

% ha = tight_subplot(Nh, Nw, gap, marg_h, marg_w)

allows me to specify the number of horizontal axes, the number of vertical axes, the gap as a scalar (or as a vector of horizontal and vertical gap values, [gap_h gap_w]), and the height and width margins. And, of course, it conveniently returns a vector of handles to the axes.

By default, the axes spacing is tighter than subplot's:

tight_subplot(2,2);

yields

Compare that to:

figure
for ii = 1:4
subplot(2,2,ii);
end

and you can clearly see how the function got its name.

Better still, ask tight_subplot for custom spacing:

figure;
ha = tight_subplot(2,2,[0.05 0.025],0.05,[0.3 0.05]);

creates a 2x2 array of axes with a normalized horizontal gap of 0.05; a vertical gap of 0.025; an equal height margin (top and bottom) of 0.05; and unequal width margins--0.3 on the left, and 0.05 on the right.

Pekka's function affords great control beyond just making a tight array of subplots. Thanks for sharing it, Pekka! And thanks (again!) to Frank Engel for the nomination. Swag on the way to both of you!

Please continue to steer us to your favorite File Exchange submissions ...we'll continue to consider your recommendations for Pick-of-the-Week recognition!

Get the MATLAB code

Published with MATLAB® 7.14