Code covered by the BSD License  

Highlights from

4.7 | 11 ratings Rate this file 332 Downloads (last 30 days) File Size: 4.82 KB File ID: #27389
image thumbnail



Simon Henin


28 Apr 2010 (Updated )

Creates a legend with a specified number of columns

Editor's Notes:

This file was selected as MATLAB Central Pick of the Week

| Watch this File

File Information

UPDATED 04/09/2013.
Thanks to comments for bug fixes/improvements.

Creates a legend with a specified number of columns


       legend_str = [];
       for i=1:10,
            x = 1:i:(10*i);
            plot(x); hold on;
            legend_str = [legend_str; {num2str(i)}];
       columnlegend(3, legend_str, 'Location', 'NorthWest', 'boxon');

PRINTING: If you want to print the figure, you'll have to use a command line printer (e.g. export_fig) as the File->Print option embedded in the figure resets the figure properties including the legend


This file inspired Grid Legend A Multi Column Format For Legends.

MATLAB release MATLAB 7.7 (R2008b)
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (33)
05 Feb 2014 Thomas van Dijk

Thomas van Dijk

Dear reader,

I tried to plot the exact code as you wrote it but get the error: Undefined function 'columnlegend' for input arguments of type 'cell'.

Error in test (line 9)
columnlegend(3, legend_str, 'Location', 'NorthWest', 'boxon');

Does anyone have a suggestion what it might be?

Comment only
10 Jan 2014 Matthew


This is a great tool for relatively simple needs, but I found immediately that I can't do much additional legend customization. Just doing
set(lh,'fontsize',8) caused my legend to revert to a single column. Could you include more input options or perhaps make the legend in a way that changing other properties won't affect the layout?

09 Jan 2014 laoya


That's great! Thank you very much.
I wish it also support 'Best' location like the legend of Matlab.

30 Dec 2013 Jhabriel


It works very fine with me, I highly recommend to use export_fig to print the plots. I think that it will be a nice improvement if we can pick a 'North' location for example, 'cause if you need to put in the middle of the figure you must move the legend with get 'Position' and set 'Position'. Best Regards Simon.

14 Nov 2013 Morten


@Aslak Grinsted
I you want to give it a vector of handles like you can do in the legend function, its a small change in columnlegend.m
first give it a extra input, e.g. 'hdl' in line 1:

function legend_h,object_h,plot_h,text_strings] = columnlegend(numcolumns, hdl, str, varargin)

and then change line 49 as well to:

[legend_h,object_h,plot_h,text_strings] = legend(hdl,str);

Comment only
31 Oct 2013 Pavlov


Hey there,

I revisited this function today after writing a script to make some custom bar graphs. Anyways, I tried running this function to make a 2-column legend, but hit an error. I then ran the simply code you provided above, and hit the same error, which is:

Error using hg.hggroup/get
The name 'xdata' is not an accessible property for an instance of class 'hggroup'.
Error in columnlegend (line 61)
xdata = get(object_h(numlines+1), 'xdata')

I may try fiddling some more tomorrow, but this is only a matter of convenience to make the plot prettier, so if there isn't a simple fix I'm missing no worries about responding.


Comment only
17 Oct 2013 Simon Henin

Simon Henin


As you know, this error is a general MATLAB error when it cannot find the function in its path. The reason why it is 'double' is because the first argument of columnlegend is a figure handle cast as a double.


Comment only
16 Oct 2013 Pavlov


I know from trial-and-error that this error just has to do with pointing to the right folder in matlab, but it just isn't clear exactly what this has to do with the double format. I know double has to do with exactly how the info is being saved or read by matlab, but it's still mysterious to me exactly what double is or at least when/why this format is needed.

Comment only
16 Oct 2013 Pavlov


Actually, this is my error:
"Undefined function 'columnlegend' for input arguments of type 'double'. :

It's not clear to me what makes the input argument('leg_str') a double type of variable. I tried num2str(leg_str) as well.

Comment only
16 Oct 2013 Pavlov


New to matlab here, but this function will be very convenient for me to use. I get the following error whether I copy/past your code here, or call the function using my own str:

Undefined function 'columnlegend' for input arguments of type 'cell'.

Comment only
13 Oct 2013 Sebastien Corner

Sebastien Corner

I forgot, you ll have to go also to the print function, highlight print and ctrl+D and comment line 293
% pj = restore( pj, h );

Comment only
13 Oct 2013 Sebastien Corner

Sebastien Corner

For those who has a problem with printing when changing the legend, I find a solution.
insert this after legend is created inside the function columnlegend

pt = getprinttemplate(gcf);
cd('C:\Program Files\MATLAB\R2012a\toolbox\matlab\graphics\private')

and copy past the legend command

lin0 is your main directory.
Also you may want to run Matlab as Administrator.
The raison the legend is modifyind when printing is because print function will set the front weight , name, of your text inside the legend. If this is modify the legend come back to its original position.
try this
set(legend_h1,'FontName', 'Helvetica')
you will see the legend will reset.
I modify the function also such that I create the legend in my script and insert it as a parameter inside the function . I inserted the 3 lines solution between the creation of the plot and my call for columnfunction.
If you have any pb I ll be happy to help

Comment only
05 Aug 2013 Simon Henin

Simon Henin

@ Mik

Thanks for your comment. Not included in the documentation is the fact that the function returns the legend's object handles. Therefore, you could alter these properties on your own.

Something like this would do it:

[legend_h,object_h,plot_h,text_strings] = columnlegend(...);

set(legend_h,'box','on', ...
'color','y', ...
'ycolor','m', ...
'xcolor','b', ...

Comment only
05 Aug 2013 Mik Mønsted

Mik Mønsted

Hey. Very nice function. Just what i needed.
Is there any way to make it non-transparent? My graphs are making the text somewhat illegible.

07 Jul 2013 Wasim Malik

Wasim Malik

I'm getting this error (using Matlab R2013a):

Error using hg.hggroup/get
The name 'xdata' is not an accessible property for an instance of class 'hggroup'.

Error in columnlegend (line 61)
xdata = get(object_h(numlines+1), 'xdata');

Any clues? Thanks!

Comment only
04 Jul 2013 Lukas Halagacka

Lukas Halagacka

Hi, very nice part of code! But the columns of legend are put together ones the .eps figure is printed. Do you have any idea how to fix it?


30 Apr 2013 Thomine Stolberg-Rohr

Thomine Stolberg-Rohr

10 Apr 2013 Ligong Han

Ligong Han

very useful

27 Sep 2012 Mai


I want to change the fontsize of the legend to 14, is that possible?
The text is to small to see in a document, the way it is.

Comment only
13 Jun 2012 Bill


I found a bug of this program. For example, when you try to change 1_by_2 legends to 2_by_1, this program will not work. Because the numpercolumn is 1, and the col is always -1.

Replace the code

if mod(i,numpercolumn)==1,
col = col+1;


if numpercolumn>1,
if mod(i,numpercolumn)==1,
col = col+1;

to kill this bug.

13 Jun 2012 Bill


20 May 2012 Durga Lal Shrestha

Durga Lal Shrestha

The columnlegend hides the box around the legend as it is not possible to force the box to be smaller than the
original height. The work around to display box is to use annotation.

The following code can be added at the very end of "columnlegend" to show the box around legend:

pos = get(legend_h, 'position');
orgHeight =pos(4);
pos(4) = orgHeight/numlines*numpercolumn;
pos(2)=pos(2)+ orgHeight-pos(4);

Comment only
16 Mar 2012 Javier Pacheco Labrador

Hi Simon,

I mixed line plots and scatter plots, what a pitty.

Anyhow, the function is great.



Comment only
16 Mar 2012 Simon Henin

Simon Henin

@ Javier

Unfortunately, at this time this script only works for line graphs, such as created via the plot command. You were probably trying to use the script on a bar or other non-typical matlab figure object.


Comment only
16 Mar 2012 Javier Pacheco Labrador


I am having a problem with one of my graphs:

??? Error using ==> get
There is no 'xdata' property in the 'hggroup' class.

Error in ==> columnlegend at 42
xdata = get(object_h(numlines+1), 'xdata');

I dunno the reason. The function works with the example on

Comment only
06 Mar 2012 Sturla Kvamsdal

Sturla Kvamsdal

Update: The problems probably has nothing to do with subplots (tried it in a simple example). Error message:
??? Index exceeds matrix dimensions.

Error in ==> columnlegend at 77
set(object_h(linenum), 'ydata', [(height-(position-1)*sheight)

06 Mar 2012 Sturla Kvamsdal

Sturla Kvamsdal

Brilliant, just what I need. Have problems with subplots, though.

Comment only
06 Dec 2011 Simon Henin

Simon Henin


Please refer to the full file description. To export to vector graphics files, use an advanced figure export (I recommend export_fig,

Comment only
06 Dec 2011 Mathias Vanwolleghem

Mathias Vanwolleghem

not compatible with eps format.
So not useful to generate figures to be included in latex documents....

Comment only
05 Sep 2011 Aslak Grinsted

Aslak Grinsted

Nice, useful and compact code! It would be nice if i could give it a list of handles to put in the legend.

Comment only
08 Feb 2011 Simon Henin

Simon Henin

Thanks for the comment, this has been fixed.

Comment only
08 Feb 2011 Amy


Nice, but doesn't work if you have used markers.

Comment only
06 Jul 2010 Martyn Dorey

Martyn Dorey


30 Apr 2010

Removed Mac OS hidden files from zip file.

11 May 2010

Add instructions for printing figure with columns

08 Feb 2011

Added functionality when using markers.

10 Feb 2011

Minor bug fix

28 Feb 2011

removed hidden files.

09 Apr 2013

Updates/Bug Fixes

14 Apr 2013

Bug fix

Contact us