Code covered by the BSD License  

Highlights from

4.7 | 16 ratings Rate this file 376 Downloads (last 30 days) File Size: 4.82 KB File ID: #27389 Version: 1.9
image thumbnail



Simon Henin (view profile)


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 and Freelegend(Hline,Hax,Hf,Str,Posi,Varargin).

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 (40)
01 Sep 2015 Daniel

Daniel (view profile)

Some posts have asked about font size adaptation, and I have also required this. I added a simple workaround (which is a bit bodged, but works for my purposes). You can add a search condition in the first switch loop :

case 'fontsize'
fsize = varargin{i+1};

Then you can set your fontsize after the basis legend is contructed:

%create the legend
[legend_h,object_h,plot_h,text_strings] = legend(str);

You can call the modified function as normal with the additional fontsize spec:



Comment only
31 Jul 2015 Wenwen Li


I call this function as columnlegend(2,legendNames,'Location','NorthWest'); However, I got an error as follows.

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

Any clue?


Comment only
25 Jun 2015 Sébastien Martin

Good job for creating the layout.

Some modifications can be made to handle scatter plots, which consist of only one element in legend (linenum = linenum+1;)
I haven't tried with other types of plots

26 May 2015 Chen

Chen (view profile)

very good!

20 May 2015 Alceu Costa

Alceu Costa (view profile)

Very useful and simple to use.

11 May 2015 Tamara Schapitz

This works out great! The only thing I would like to change is, that the legend can also be located outside the diagram (e.g. 'southwestoutside')

The only possible values at the moment are: 'NorthWest', 'NorthEast', 'SouthEast', 'SouthWest'
Could somebody help me, at which point I would have to adapt the code?

01 Mar 2015 jun jun  
05 Feb 2014 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

laoya (view profile)

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

Morten (view profile)

@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

Pavlov (view profile)

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 (view profile)


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

Pavlov (view profile)

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

Pavlov (view profile)

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

Pavlov (view profile)

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

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

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 (view profile)

@ 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

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

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

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  
10 Apr 2013 Ligong Han

very useful

27 Sep 2012 Mai

Mai (view profile)

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

Bill (view profile)

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

Bill (view profile)

20 May 2012 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 (view profile)

@ 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

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

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

Comment only
06 Dec 2011 Simon Henin

Simon Henin (view profile)


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

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 (view profile)

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 (view profile)

Thanks for the comment, this has been fixed.

Comment only
08 Feb 2011 Amy

Amy (view profile)

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

Comment only
06 Jul 2010 Martyn Dorey


30 Apr 2010 1.1

Removed Mac OS hidden files from zip file.

11 May 2010 1.2

Add instructions for printing figure with columns

08 Feb 2011 1.4

Added functionality when using markers.

10 Feb 2011 1.5

Minor bug fix

28 Feb 2011 1.6

removed hidden files.

09 Apr 2013 1.7

Updates/Bug Fixes

14 Apr 2013 1.9

Bug fix

Contact us