Code covered by the BSD License  

Highlights from


4.3 | 6 ratings Rate this file 25 Downloads (last 30 days) File Size: 165 KB File ID: #34191
image thumbnail




13 Dec 2011 (Updated )

A subplot figure with a lot of fancy features

| Watch this File

File Information

SUBPLOT_GRID is a class with which a set of subplots can be created in a space-optimal way. In addition, a figure title and subtitle may be added, as well as specific row and column titles.
Even after resizing, the texts ((sub)figure title and row and column titles) are NOT scaled, keeping the maximum space for the axes.
The SUBPLOTZOOM (combined with maybe ZOOMLINK_aXES) function enableS filling the figure window with one or more axes.
The INTERAXES function provides the possibility to show the clicked on data point in an axes, and to shows its values in the title.
The methods LEGEND and COLORBAR ensure a correct handling on zooming and resizing.

Available methods (listed alphabetically):

COLORBAR - creates a colorbar to an axes
COLTITLES - Adds column titles (top and bottom are possible, locations can be manually set)
FIGTITLE - Adds a figure title
SUBFIGTITLE - Adds a subtitle
DISABLE_INTERAXES - remove clickable content
DISABLE_SUBPLOTZOOM - remove zoom action
ENABLE_INTERAXES - Enable clickable content
ENABLE_SUBPLOTZOOM - Enable figure filling zoom
EXTRACT_AXES- extract an axes to a new figure
FIGPLACE - grid the figure window or maximize the window
FIGTITLE - add a global figure title
HIDE_AXES - make some axes invisible
HIDE_EMPTY_AXES - hide all empty axes
LEGEND - add a pre-defined legend
OVERWRITE_INTERAXES_SELECTION_MODS - some user-defined modifications for clickable content (interaxes)
REDRAW - redraw the figure (re-align all)
RELOCATE_LEGEND - reset legend position
REMOVE_LEGEND - remove legend
ROWTITLES- add texts on the left/right around the axes. Location can be manually set
SET_GCA - set axes to current axes in matlab
SET_PADDING - reset padding around axes
SHOW_AXES - show hidden axes
SUBFIGTITLE - a subtitle
SYNC_AXES - sync x, y or color axes
ZOOMLINK_AXES - link axes on use of subplotzoom.

run 'subplot_grid' for a demo.

The syntax of every method can be found by 'help subplot_grid.<method>'


This file inspired Subtightplot.

MATLAB release MATLAB 8.1 (R2013a)
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (23)
03 Dec 2014 Joris Kampman

Hello everybody,

Thank you all for finding and reporting the bugs. Unfortunately I've not made the transition to version 2014 yet. However I'll get this installed shortly.

Regarding the save-figure method: I've found that there is way which allows the figure to be saved and loaded keeping all methods and properties. I've started to work on this.

I'll probably upload a new - matlab 2014 compatible - version of subplot_grid during the xmas holidays.

Kind regards


03 Dec 2014 Manuel

On the other hand, I've found a new issue. The use of the colorbar method doesn't seem to be working. Every time I try to use it I get the following error:

Error using colorbar (line 55)
Attempt to reference field of non-structure array.
Error in subplot_grid/colorbar (line 2181)
hcb = colorbar('peer',this.hax(ir,ic),location);

Had the same Problem : Don't preinitialize your axes-handles with doubles like :

h = zeros(1,3);
h(1) = subplot (1,3,1);
h(2) = subplot (1,3,2);
h(3) = subplot (1,3,3);

I got the issue with colorbar in this case, here is class (h(1)) "double" but it works without preinitialization :

clear h;
% h = zeros(1,3);
h(1) = subplot (1,3,1);
h(2) = subplot (1,3,2);
h(3) = subplot (1,3,3);

here is class(h(1)) "" like it should be.

Strange behavior in Matlab, the type "double" will not be overwritten.

14 Nov 2014 Adam

I am curious if the save_figure() feature, to enable saving and reloading to a .fig file was ever implemented, as noted in your 7/14/2014 update. I don't see the functionality in the current version of the code, and this would be very useful to me if it worked smoothly. (I get the same errors as Alex when trying to reload a saved .fig).
Great tool though!!

30 Oct 2014 Dan K

I'm sorry if I seem to be harping, but it looks like the set_padding method is not operational either. I don't find any reference to the loose_inset property in the reposition_content function. Is this something that you've worked on?


20 Oct 2014 Dan K

For my first item below, it can be eliminated by changing the code in the set_zoom_button_position as follows:

if verLessThan('matlab','8.4')
%DWK: Inlining the layering command provides modest speed improvement
% uistack(this.subplotzoom_data(ir,ic).zm_btn,'top');
parentObj = get(this.subplotzoom_data(ir,ic).zm_btn,'Parent');
allDescendents = get(parentObj,'Children');
% Only changing the layering if necessary makes a big difference
zmBtnIndex = find(allDescendents == this.subplotzoom_data(ir,ic).zm_btn,1);
thisAXIndex = find(allDescendents == this.hax(ir,ic),1);
if zmBtnIndex < thisAXIndex,
newOrder = [allDescendents(allDescendents~=this.subplotzoom_data(ir,ic).zm_btn);this.subplotzoom_data(ir,ic).zm_btn];

On the other hand, I've found a new issue. The use of the colorbar method doesn't seem to be working. Every time I try to use it I get the following error:

Error using colorbar (line 55)
Attempt to reference field of non-structure array.
Error in subplot_grid/colorbar (line 2181)
hcb = colorbar('peer',this.hax(ir,ic),location);


17 Oct 2014 Dan K

Just wanting to touch base here, in that I think it could use a bit of work to be more R2014b compatible. The issues that I'm seeing are:

1. A lot of warnings...
Warning: Illegal permutation. No effect on view
> In subplot_grid>subplot_grid.set_zoom_button_position at 2780
In subplot_grid>subplot_grid.reposition_content at 2620
In subplot_grid>subplot_grid.subplot_grid at 680

2. The appearance of a background axis object behind the grid.

Unfortunately I don't have the time to try tracking it down now, but I thought I would mention it.

As always, many thanks.

21 Aug 2014 Joris Kampman

hello Vincent,

Thank you for the feedback and nice rating.
It's funny to notice that the
thing you like about the way matlab creates legends is exactly why I dislike it.

I agree that when you change the color of a graph, the default legend will change automatically and this can surely be handy. However to me this often spells trouble and was the reason to do it differently. I therefore opted for a legend that is NOT directly coupled to the data.

I'll try to seewhat I can do,however,I seriously doubt I can do a lot since the default legend is not linked to a specific axes via a property or something.

But I'll give it a go.

Please check the updates or my comments in case it is not possible or practically feasible.

kind regards

19 Aug 2014 Vincent

Thanks Joris for the nice submission.

It would be nice if it the zooming would also work with the default legend. I like this default Matlab legend because it's coupled to the data, when i edit it, the colors change too. But when pressing the zoom button, normal legends don't disappear.

23 Jul 2014 Joris Kampman


after construction of a subplot_grid object, the current axes was not always rightly defined. This is fixed, and set to the first subplot after construction.

the use of the method set_gca is now not needed after construction (i.e., if the first subplot is the first to be used).

14 Jul 2014 Joris Kampman

I've fixed the bug and added the option to save as a .fig file and load without errors. It even does all things it did before. The methods can be accessed similarly.

In addition, I've made the row and columns texts to work on all 4 sides (top, bottom, left and right) and you have the possibility to position them manually. The coupling between number of subplot rows/columns and number of titles is removed.

27 Jun 2014 Joris Kampman

Hello Alex,

Thank you for the kind words. I really appreciate your comments and found bugs. I'll try below to answer them clearly.

1. This is clearly a regression bug (which I'd fixed internally without feedback to matlabcentral.. whoops!). I've by now submitted an update (version 4.8, to see in the class property 'version'). The syntax you used is correct!.

2. I'm also not an expert on classes. But being a simple guy, I see class properties as 'global' variables within the class and methods as functions within the class. For modifications on data by different methods classes are perfect and therefore used here.

To get the value of a property at any time during the processing simply type <obj>.<property> and you have the value. Thus for the hax property <obj>.hax. You're right that this property is needed sometimes (as is 'current_axes' and the 'set_gca' method). running a methods is done similarly. See 'help subplot_grid.<method>' on the method syntax.

3. My colleagues asked me the same question, so I'll spend some time on this. An update shall have this feature implemented in the near future (i.e., weeks not days ;)).

on the bug:
You're fully correct that this is annoying, but I must admit I simply save the figures immediately as png/jpeg (via 'export_fig') and therefore never have this problem. However, this should be corrected if possible (howeve, not being a class expert I wonder if it is!).
I'll try to find a way to do this correctly and - if possible - will implement a fix.

kind regards,


23 Jun 2014 Alex


Thank you for developing this most excellent tool for making subplots! I wish I had known about this back when I started my research. It's a very robust program and I'm still discovering what it can do. That said, I do have some questions and would like to inform you of a bug I stumbled on.

First, the questions:
1. What is the proper syntax for the "cell array of vectors" used for mergelist (or zoomlinklist)? Do the vectors need to be a certain length? The following produces an un-merged 3X4 grid and gives me an "index exceeds matrix dimensions" error (pointing to line 422):

obj = subplot_grid(3,4,'mergelist',{[3 4],[7 8]})

2. I'm a total novice with Matlab Class Objects - how is a Class different from other data types? Also, I don't have an immediate need for it, but what is the correct way to access the "hax" matrix? It seems like something that would come in handy for more complex programs.

3. More of a comment/suggestion than a question, but I really like the fact that the title methods, like rowtitles and columntitles, can take a nested cell array, which allows for stacked text in these areas. I used the following to add an "axis" label for all of the rows, with an extra space between this and the other three labels:

obj.rowtitles({{'','','2D Global'},{'Depth (m)','','3D Global'},{'','','3D Array'}})

You could probably add a another method to make an "overall" row title. If you want to keep it centered, the above works just fine when you have an odd number of rows (which I do). An even number would require a separate method to ensure that the "overall" title was centered between rows. I used subfigtitle (without a figtitle) to put an "overall" label on the columns. Instead of a big overhead figtitle, I save each figure as a .png and insert into my thesis, where add a caption under it.

Now, the bug: I have made a few figures with subplot_grid and saved them as both .fig files (so I can return and edit them as needed) and .png files for my thesis. When I come back later and try to open the .fig, the top row of subplots moves behind (and slightly below) the last row of subplots and Matlab spits out the error text below. I used a script to produce these files, so I can always go back and re-plot them, but I would rather make the changes on the already-created figures. You really to have an excellent program here, and I would give it 5 stars if it wasn't for this (.fig file) issue.



(p.s. Matlab error text below...)

Error using handle.handle/get
Invalid or deleted object.

Error in subplot_grid/subplot_resize_fcn (line 2282)
tmp = get(this.hax_coltitles(1),'Position');

Error in subplot_grid>@(src,evt)this.subplot_resize_fcn (line 467)

Error using set
Error while evaluating figure ResizeFcn

Error using handle.handle/get
Invalid or deleted object.

Error in subplot_grid/subplot_resize_fcn (line 2282)
tmp = get(this.hax_coltitles(1),'Position');

Error in subplot_grid>@(src,evt)this.subplot_resize_fcn (line 467)

Error using figure
Error while evaluating figure ResizeFcn

Also, when I close the mangled figure, similar text to the above appears four times saying "Error using delete"

16 Jun 2014 Joris Kampman

Hello Christoph,

Of course I'd like to help you, but what kind of instructions are you looking for?

It could be that you're not used working with classes? Or do you need some syntaxes to get you started?

Have you tried "help subplot_grid' or in case you need some help with a certain method you could try "help subplot_grid.<method>"

13 Jun 2014 Christoph


I have a question. Your Subplot_grit tool looks really nice and I was searching for something like that. But do you have some kind of instructions for beginners with your code? Would be very nice.
Nice Regards,

14 Feb 2013 Dan K


Here's a thought for you: Have you considered setting it up so that the grid can live inside some other parent besides its own figure? I'm setting up a GUI, and I'd like to consider putting a grid inside a uipanel.... Thoughts?

25 May 2012 Dan K

Sorry about that last. Hit return by mistake. Joris, I've run into an issue using subplot_grid, which may be fairly unique, but I thought I would mention it. In order to save figures and be able to change them later, I'm using setappdata to copy the subplot_grid object into the figure's appdata. However, this has an interesting consequence: After I've cleared the figure, the object which is saved in the application data is still listening for callbacks, such as resize, and throwing an error:

Cell contents reference from a non-cell array object.
Error in cell2mat (line 43)
cellclass = class(c{1});
Error in subplot_grid/reset_handles (line 3279)
positions = cell2mat(get(haxs(:),'OuterPosition'));
Error in subplot_grid/subplot_resize_fcn (line 2153)
Error in subplot_grid>@(src,evt)this.subplot_resize_fcn (line 429)

I'm looking for a place where I can test to check if the object is still referring to a valid grid, and abort. An alternative would be to find a way to clear out the appdata on a clf. If you have any suggestions, I'd appreciate it.


25 Apr 2012 Karl

The demo really shows what this can do. However, it doesn't show how to do it. I would probably increase my rating to a 5star if there were examples to go along with the function.

16 Apr 2012 Dan K

Again, I applaud your good work. This has rapidly become one of my favorite FEX functions.
Another items to think about adding when you get around to it:
I would find it useful to be able to create a shared xlabel (much like the coltitle method) only at the bottom of the figure.

02 Mar 2012 Joris Kampman

I've uploaded a newer version (internal version 4.4). I've been able to fix the bugs found, except the problem with PLOTYY which uses two overlaying transparent axes. This is quite horrible for the script, so I really have to think about this, and for sure this will have a BIG impact on the function.

The addition of a COLORBAR was done and a method SET_PADDING to control the padding between axes.

However, a combination of all possible actions was not done, so please keep me informed on found errors/bugs

01 Mar 2012 Dan K

I've come across another item that could use a little work. If you clear a figure that used to have a grid, it fails anytime on account of the resize function (see below). I think this could be resolved with an appropriate destructor method.

Again, thank you for your great work.

Error using handle.handle/get
Invalid or deleted object.

Error in subplot_grid/resize_wo_legend (line 3129)
units = get(this.hax(ir,ic),'Units');

Error in subplot_grid/subplot_resize_fcn (line 1986)

Error in subplot_grid>@(varargin)this.subplot_resize_fcn(varargin{:}) (line 399)

Error using drawnow
Error while evaluating figure ResizeFcn

23 Feb 2012 Fernando  
22 Feb 2012 Fernando

Colorbar position are not respected when resizing and their labels appear on top of next subplot ticklabels or outside the margins of the figure

14 Feb 2012 Dan K

Very nice work... A couple of (maybe) suggestions. (Maybe, because they might already be implemented, and I just didn't find them). Create an output for the set_gca method which is the handle of the axes you just selected (useful for titles,TickValues, etc.) Also, allow some control over the amount of whitespace between axes. It also really seems to dislike plotyy. But all told, it's one of the better subplot functions I've seen.

25 Jan 2012

some bugfixes on legend placements, and the correct working with zooming in and out.

02 Mar 2012

1: Matched the legend style to MATLAB
2: Bugfix in the legend placement
3: Added correct handling of axes deletion.
4: Added COLORBAR method.
5: Added SET_PADDING which allows control over the amount of whitespace between axes

26 Apr 2013

-speed improvement (thanks to Dan Kominsky)
-added method COLORBAR
-added possibility to link axes on zooming in

27 Jun 2014

see 'help subplot_grid'

27 Jun 2014

very stupid bug fixed (seen when only plotting a single axes (subplot_grid(1) crashed)

14 Jul 2014

1. possibility to save a .fig file and load without errors
2. very flexible row and column titles on all 4 sides.
3. different resizing scheme (more robust)
4. minor bugfixes

23 Jul 2014

fixed minor irritation. Now, after construction of a subplot_grid object, the current axes is set to the first subplot, instead of being left undefined

Contact us