version 1.1.0.0 (2.03 KB) by
Pekka Kumpulainen

Fills the figure with axes subplots with easily adjustable margins and gaps between the axes.

**Editor's Note:** This file was selected as MATLAB Central Pick of the Week

Subplot tends to leave a lot of empty space around the axes. Tight_subplot allows to adjust the spacing between the axes as well as the margins around the axes.

For example:

[ha, pos] = tight_subplot(3,2,[.01 .03],[.1 .01],[.01 .01])

for ii = 1:6; axes(ha(ii)); plot(randn(10,ii)); end

set(ha(1:4),'XTickLabel',''); set(ha,'YTickLabel','')

Pekka Kumpulainen (2020). tight_subplot(Nh, Nw, gap, marg_h, marg_w) (https://www.mathworks.com/matlabcentral/fileexchange/27991-tight_subplot-nh-nw-gap-marg_h-marg_w), MATLAB Central File Exchange. Retrieved .

Created with
R2010a

Compatible with any release

**Inspired:**
COVID-19 World Spread Animation, imageslices, Tight subplot with units in centimeter, smplot for small multiples, subtightplot, tightPlots, Correlation Matrix Scatterplot

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

Start Hunting!Create scripts with code, output, and formatted text in a single executable document.

Arthur ChavignonDavid BodineGreat, very useful!

zhiwen wangDominika ThiedeI have a 2x1 subplot and I want the height of the 2nd subplot to be 1/3 of the height of the first subplot. The distance between the subplots should not change. Is that possible?

Zeynab MousavikhameneYangEdmund PickeringDonald Romarick ROTIMBO MBOUROU (diy-aeq.com)Dear developper,

Good job! This is a nice function when you can plot several figures for better comparison.

Thank you verry much for your sharing!

Aleix Parísyong wangJonah PearlThis works wonderfully! MATLAB gives the warning "called axes(h) in a loop can be slow." Is there a way to avoid having to call axes?

Oscar Sepulveda Steinerlaurent jalabertmmm ... with 21 subplots, it seems to have some trouble. Please try this code :

ha = tight_subplot(3,7,[.01 .03],[.1 .01],[.01 .01])

for ii = 1:21; axes(ha(ii)); plot(randn(10,ii)); end

set(ha(1:4),'XTickLabel',''); set(ha,'YTickLabel','')

matt majicYangYangSkliUoDMartin MuellerPeter Cairiccardo scandroglioJohannDear Pekka, assuming a classic subplot figure of 3 rows and 2 colums, how can you set a sort of:

subplot(3,2,[1:2]) ????

It was not possible to span a single figure onto two consecutive panels vertical or horizontal?

Thanks a lot for your comments and obviously for your nice contribution.

Kaushik SampathVadym FarynaXiaolinSantiago RodriguezXingwang YongEthan KyzivatJérôme BarangerExactly what I needed, thanks a lot.

Jake ChalouxWorked like a charm! Thanks for sharing

Sia XieyunDaniel BroullónNicolaj Hansensezen onolYingxuan WangDanny AllenDimitrij ChudinzowMarc Fivazant0nisSiyao HuOliver PaulAndrea JenneyEasy to use! Question: some of my subplots will not show when the panels are close together (e.g., gap = 0). I am able to get around this by increasing the gap or margins along the edges. Is this a bug that can be addressed? Or does anyone else experience this and know a simple and fast solution?

Seyed Ali Baradaran BirjandiZhao HonglongThank you so much for sharing with this function!

Anders BergUrban WünschPlease note that sometimes the TickLabels get removed using this function and if you want them printed reliably using e.g. export_fig, you have to call:

set(gca,'XTickLabel',cellstr(num2str(get(gca,'XTick')')))

set(gca,'YTickLabel',cellstr(num2str(get(gca,'YTick')')))

This seems to be the only workaround that does not cause issues with wrong! ticklabels. Watch out!

Wang MenglingGreat function! Thanks a lot!

zy hangreat job.

SHAOXIN HUANGsaeed mMehmet Emin MumcuogluPhillip ColmersPakorn WongwaitayakornkulGabriella NyitraiSara MolinariMahdi TorabiThanks for the helpful script. Is there any way to add one common suplabel for all X and Y axis using this? Using other apps make extra space.

Shahrin IslamHello. I am a new learner. I need to concise my subplot. Please help me with my code attached following. I don't understand how can I use the above function with my code. Please help me.

% Display the original Image

image = imread('boardday.jpg');

% Read Colour Image and convert it to a grey level Image

myimage = rgb2gray(image);

figure;

subplot(2,1,1);

imshow(image); title ({'Original';' Image'});

subplot(2,1,2);

imshow(myimage);title({'Gray Scale';'Image'});

Chris Personsidan barazaniVictor Hugo SouzaVery useful function! Congratulations.

Punnag ChatterjeeBob DAMengyao LengIt's so useful with very concise calculation.

Peter GormsenGreat tool! Thank you very much

Heather MillerTian LanYochai BlauGreat function. Thanks!

Adam DanzThis method is intuitive and easy to use. I just wish the XTickLabel and YTickLabel weren't empty after creating the axes. To put them back on, you should call this on each axis:

set(h, 'XTickLabelMode', 'auto')

set(h, 'YTickLabelMode', 'auto')

Changyong HeGeorg WioraEmmanuel BossJohann MARTINEZMerci pour votre contribution! ;)

Roxana StefanescuThis is an excellent function!! Thank you so much for your post!! :-)

Sebastian Kukla@Megan Fowler

You might use a combination of set and get. This worked fine for me.

originalSize = get(gca, 'Position');

cb = colorbar;

set(gca, 'Position', originalSize);

matThanks!

Megan FowlerThis is very helpful! One issue I'm unclear on is how to add a colorbar to one subplot without screwing up the alignment with all the other panels in the figure - is there a fix for this?

Jonas Steinthank you. PS: The ';' behind the three if-lines are unnecessary.

if numel(gap)==1;

...

bravomuseReally useful, thank you!

Grzegorz KnorMr.Leung非常感谢作者提供的函数命令，非常有用！（thank you so much for your this code,it is very helpful to me!）

Jonathan BentThis really made my dissertation work come together nicely. I've used it hundreds of times, and appreciate it hugely! One question now that I'm using the function to generate some different plots: is it possible to specify that the bottom of two subplots take up less of the figure area than the top? I.e. the top plot would have, say 500 pixels in height, and the bottom 200? Cheers.

mochaABehroozgregaShawn Mikulajose mejiaAndrew DiamondNice but I had to add a shift parameter to stop my tick labels on the left from being truncated (as per below where the "bias" parameter is a new 2 element vector input arg and just added to the position as follows

'Position',[px+bias(2) py+bias(1) axw axh], ...

I guess it would be nice to have it totally auto centered (not that I know how off the top of my head) but I'm just really happy that you wrote this. Thanks.

Pekka KumpulainenThis function does not follow subplot's default syntax because this is not subplot but another function. The third input argument is the gap between axes. Not the number-in-order of the axis to set as 'CurrentAxes' of figure as in subplot. See help for description of the input arguments.

There seemed to be an ancient version in Fex, I updated a mre recent version, which makes it easer top live with colorbar and other functions, which modify the positions of existing axes.

SLA discussion about the problems in the subplot here http://stackoverflow.com/q/35770961/54964 where colorbars with an example and subplot's 3rd parameter are discussed.

SLDoes not follow subplot's default syntax by omitting the third parameter. Fails with colorbars.

SLMulberry SonPerfect! Thank you!

Junia Josephine DK EYou can find tightfig.m here, http://www.mathworks.com/matlabcentral/fileexchange/34055-tightfig

pingfanyuUndefined function or variable 'tightfig'.

Why i encountered this problem and how can i do?

Natanthis is one of the most useful FEX contributions I have ever encountered. Thank you for the effort!

Ashley ZhangExcellent function!

Yet I have one problem. When I plot odd number of subplot, say 7 plot arrayed as 4*2, there is always one blank plot that I cannot remove even though I delete the last value in ha.

Any one have any idea to fix it?

* Problem fixed by setting axis, XColor and YColorthe of the last plot invisible.

subplot(ha(8)); set(gca,'Color','none','XColor','none','YColor','none');

Naveen GowdayyanadoddiExcellent function. Works fine for me.

TeroFeedMeImATrollExcellent function, thanks. The one thing I am missing: Is there a way to connect different subplots, as in subplot(4,2,[1,3,5])?

hadiPettertnx, great job

Enrico FondaRinaPanagiotis Papagiannopoulosthis file really helped me! however i have one question. i want to set fixed limits of the x,y axis in each subplot.For example: (axis([0 700 -500 10000])).i tried to do it but with no result. any advice of how can i do this?

Ahmed FasihBethFelipe G. NievinskiIt's great that it offers variable outer margins in addition to inner gaps. I wish it could support asymmetric plots, where a panel spans multiple rows/columns, though.

Lucas KoorneefPhilip ValenciaNice, very handy, though by default I prefer my tick labels left on... others who want this might just mod the file.. just remove in the inner loop where it sets the ticks off... i.e.

for ix = 1:Nw

ii = ii+1;

ha(ii) = axes('Units','normalized', ...

'Position',[px py axw axh]);

px = px+axw+gap(2);

end

ThomasGal Haspeluseful and does what it claims

GiovanniThis is a great script. I'm experiencing a bug that makes my ticks disappear. Here's a sample:

figure('position',[100 100 1000 600])

ha=tight_subplot(1,3,[.02,.02],[.12,.08],[.1,.02]);

for a=ha'

hold(a,'all')

box(a,'on')

xlim(a,[.1 10])

ylim(a,[-90 10])

end

set(ha,'xscale','log','fontsize',fontSize,'ytick',-100:10:20,'yticklabel',[],'yminortick','on')

set(ha(1),'yticklabel',-100:10:20)

% 1

scatter(ha(1),x11,10*log10(y11),30,[0 .5 0],'x');

scatter(ha(1),x12,10*log10(y12),30,[0 0 1],'filled');

% 2

scatter(ha(2),x21,10*log10(y21),30,[0 .5 0],'x');

scatter(ha(2),x22,10*log10(y22),30,[0 0 1],'filled');

% 3

scatter(ha(3),x31,10*log10(y31),30,[0 .5 0],'x');

scatter(ha(3),x32,10*log10(y32),30,[0 0 1],'filled');

I would expect to see xticks at .1, 1 and 10, but on my system they simply disappear. If I tried and add them manually the log scale gets screwed up, so there's gotta be another way around. I'm using Matlab R2012a.

Thanks!

MarinReally excellent file, thank you. Maybe an extra example wouldn't be a bad idea in the comments for the new Matlab user to better learn to use this file.

I have two questions though if I may ask them here...

1. How do i add numbers on the y axis? (only on the rightmost side of course)

2. How do I write x & y labels? (only one that applies to all axis)

Thank you in advance.

alexpapiKevin ClaytorVery nice, needed something exactly like this, and it's quite easy to use.

Jiangmin zhangi cannot do anything but give a five star! absolutely smarter than mathworks!

AdityaHey,

Great function. Pity I came across it after I spent much of my time writing a similar function. As some people have said above, I wanted the function to work with multiple rows/columns spanning subplots. So I included that capability in the following function:

http://www.mathworks.com/matlabcentral/fileexchange/35464-spaceplots

Just thought it might be useful to some.

KarlI second what Dan said. Spanning multiple columns/rows would be really useful. For example:

ha = tight_subplot(2,2,0.1,0.1,0.1)

axes(ha(1));plot(x1,y1);

axes(ha(2));plot(x2,y2);

axes(ha([3 4]))plot(x3,y3);

Rakesh ChalasaniRaviThanks a lot for the script.

Matthew SchroederGreat work. Would be nice to be able to have the subplots fill a uipanel instead of the entire figure (doesn't play with within a GUI).

Matthew SchroederCarlos BaizDanNice function, and one that I've come to rely on. It would be great if axes could span multiple columns/rows as you can do using the built-in subplot. Otherwise, great.

Brent BoehlertOops -- didn't know that rating the submission meant submitting. Excellent function that saved me tons of time in having to generate graphics through GIS. No clue why the subplot command has this issue, but thanks for addressing it!

Brent Boehlertkos goEinar OlasonExcellent little script! Thanks a lot!

Still, I have one suggestion: Instead of saying "axes(ha(ii));" in the example a better way may be to say "subplot(ha(ii));". Using axes gave me unpredictable behaviour when setting up two plots side by side. I would (almost always) plot to the axes on the right, no mater how often I tried giving the "axes(ha(1))" command (or "axes(ha(2))" for that matter). Using subplot solved that. Don't know why though ...

ThomasGood work. I needed to create several plots with several sub-plots within a loop. Had trouble with empty plots as the result and Matlab was broke until I restarted it. Even a plot(1:100, rand(1, 100)) would return an empty figure. Anyway, I returned the value for the axes position matrix "ha", and removed the internal axes command. When I was ready to plot in one of the figures I had being created to a specific subplot location I called:

figure(h4);

subplot('Position', ha4(fc4).pos); p=plot(1:100, rand(1, 100));

where ha4(fc4).pos corresponds to the fc4'th subplot position in figure with handle "h4".

AlexanderThank you for this contribution. I like it very much.

In my opinion the input check should be like that:

if nargin<3 || isempty(gap); gap = .02; end

if nargin<4 || isempty(marg_h); marg_h = .05; end

if nargin<5 || isempty(marg_w); marg_w = .05; end

So you can modify marg_w and take the defaults for the other parameters.

tight_subplot(nrows,ncolumns,[],[],[.1 .05]);

Alexi dont know what mathworks was thinking with their subplot routine... this is much nicer