Code covered by the BSD License  

Highlights from
gridLegend - a multi column format for legends

3.9 | 18 ratings Rate this file 233 Downloads (last 30 days) File Size: 5.42 KB File ID: #29248
image thumbnail

gridLegend - a multi column format for legends


Adrian Cherry (view profile)

  • 1 file
  • 3.94118


02 Nov 2010 (Updated )

Plot a multicolumn format legend.

| Watch this File

File Information

On a plot with a lot of traces the standard legend will often scroll off the bottom or the side of the figure, this function is intended to overcome this by allowing the user to define a multi column format for the legend.

Usage :
legHdl = gridLegend(hdl,nCols,gKey,'parameter_name','parameter_value',...);

Inputs :
hdl - a vector of graphic handles of the plotted data
nCols - the number of columns in the legend. (defaults to 2 if not defined)
gKey - a cell array of strings to display which should match the number of graphic handles in hdl (optional)
'parameter_name','parameter_value' - any parameter name pairs applicable to the legend

Output :
legHdl - a vector of graphic handles for the legend generated.

 Notes :

By default the legend will be arranged vertically, ie the second legend trace is placed under the first trace, filling the first column before moving onto the next. If you use the 'Orientation','Horizontal' parameter pair then the traces will be arranged horizontally, so the second trace will be in the second
column and so on to the end of the row, then moving down to the next row.

The parameter name / value pairs are passed over to the legend function so you can set things like 'Fontsize',8 etc.

The parameter / name pair of location can be used to place the legend - available options are
'location','bestoutside' : for 2 column legend uses 'eastoutside', more than 2 it uses 'southoutside'
'location','north' : places the legend centrally at the top of the axes
'location','northoutside' : places the legend centrally at the top of the figure
'location','eastoutside' : places the legend on the right of the figure
'location','southoutside' : places the legend centrally at the bottom of the figure
'location','westoutside' : places the legend on the left of the figure

 By default this is set to 'bestoutside'

This will work on x-y plots, bar and errorbar charts.

With many traces it's sometimes difficult to work out which trace the legend is referring to. From the MATLAB file exchange I've used a function called 'clickableLegend' which allows you to switch the plotted data on and off by clicking on the Legend key. This function will use clickableLegend if it can find it in your MATLAB path, otherwise it will revert back to the standard legend function.

Examples :

This will plot a vertical legend with two columns

This will plot a horizontal legend, 8 traces per row, and fontsize set to 8 points.

This will plot a vertical legend on the left hand side with 2 columns with the box switched off. I've fiddled with the XColor and YColor otherwise we end up with black lines for the X and Y axis.
       gridLegend (hdl,2,gKey,'location','westoutside','Fontsize',8,'Box','off','XColor',[1 1 1],'YColor',[1 1 1])


Clickable Legend and Columnlegend inspired this file.

This file inspired Axlegend.

MATLAB release MATLAB 7.6 (R2008a)
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (26)
13 Mar 2015 Nicholas

It seems that the 'dataaspectratio' property of legends has been removed in recent releases of matlab

I'm using 2014b and can not find this property, your function errors on line 232: set(legend_h,'dataaspectratio',[width/gd gd/numpercolumn 1]);

Any thoughts or suggestions around this would be helpful

Comment only
18 Dec 2014 Shuqin

Shuqin (view profile)

Wonderful! I think you solved the problem that many paper writer need to face. Thanks!

06 Nov 2014 Mahdi Ebrahimian

Hi Adrian,
Thanks for the nice function.
I want to have a row legend (three columns one row) but when I put column number equal to three I get an error message.
"Can't work out what sort of legend we've got - sorry bailing out"

Any suggestions to fix this?

04 Aug 2014 Todd

Todd (view profile)

Very easy to use and helpful. Thanks.

25 Jul 2014 Benedikt F

Did not work for a figure containing both error bar and x-y plots

10 Jul 2014 James

James (view profile)

Works very well, except when the figure is saved as a fig file. When the saved file is opened, the legend has reverted to single column. Recommendations for how to fix this issue appreciated.

Comment only
21 Feb 2014 Amanda

Amanda (view profile)

Hi, I love this function! My one big issue is that I sometimes find it hard to define a handle for the plotted data. Especially for compound graphs like a bar chart with error bars.

I get error for too many output arguments.

I am new to matlab so I hope someone could help me out here. Thank you!

09 Jan 2014 laoya

laoya (view profile)

Great jobs, thanks!
I wish the function support 'Best' like the legend function of matlab.

10 Sep 2013 Edward Byers

Doesn't work perfectly for subplots but...
I managed to get it to work reasonably well (on 1 occasion with an Area subplot) by...:
1) - Open gridLegend .m file and comment/delete line 273.
2) - If you are getting errors about Scribelegend, delete lines 278-284
3) - Specify a location (I used 'location','southoutside' )

Basically the issue with subplots (from what I can see) is that gridLegend is trying to control the 'gca' which doesn't seem to exist in subplots.

03 May 2013 Nicky

Nicky (view profile)

gridLegend doesn't seem to work when the figure contains subplots (it messes up the sizes of the subplots).
Is there any fix for this?

Comment only
10 Apr 2013 Jim

Jim (view profile)

This is a nice improvement in capability over columnLegend. Unfortunately, despite turning off the ScribeLegendListeners properties, I find that when a figure is saved and later reopened, the legend reverts to single-column format. My code has two calls to saveas near the end, one to save the figure in .fig format, and one to save it as a .emf file. Both are afflicted with single-column disease.

Comment only
21 Mar 2013 Johnny

Johnny (view profile)

Is there any way to adjust the spacing between two columns? Thanks.

28 Feb 2013 Matthias Pospiech

The script fails for my patch plots completely:

Index exceeds matrix dimensions.

Error in gridLegend (line 206)
set(object_h(linenum), 'ydata', [height-position*sheight height-position*sheight]);

Error in testplot (line 204)
legHdl = gridLegend(hplot,2,ltext)

with hplot and ltext both of size 1x6

14 Jun 2011 J G

J G (view profile)

Hi there, will this work on scatter plots? Thanks!

Comment only
29 May 2011 Bob Sturm

Bob Sturm (view profile)

Well done!

10 May 2011 sarah

sarah (view profile)

Hi Adrian,
thanks for uploading!
Any chance this can work for graphs including both lines and bars?

So far an example below doesn't produce a nice legend.

y=[2 3]'*x.^.5;
p=plot(x,y); hold on
gridlegend([p;b],2, {'line1' 'line2' 'bar'});

04 May 2011 James Hickey  
19 Apr 2011 Ruben

Ruben (view profile)

great idea, but the legend placement seems to go haywire. (at least in my case, where location is northoutside, 3 legend entries, 2 columns). Also some of the text and lines overlap.

L1 = {'Flapping angle $\Phi$ ' ,'Elevation angle $\theta$ ',...
'Feathering angle $\alpha$ '};
LH = gridLegend(fh,2,L1,'location','northoutside');

16 Apr 2011 Will DeShazer

I have found a collision. I have personalized my 'DefaultFigurePosition' to increase the figure window when it launches. It looks like:scrz=get(0,'ScreenSize');
set(0,'DefaultFigurePosition',[newxpos newypos xscale*scrz(3) yscale*scrz(4)]);

With this preference active, gridLegend generates a legend in which the text gets bunched up. As an example of something that gets bunched up:

a=[40 40 40 40:-1:21; 50 50 50 50:-1:31; 60 60 60 60:-1:41];

b=[1 2 3 ones(1,ndim-3)*4; 2 3 4 ones(1,ndim-3)*5; 3 4 5 ones(1,ndim-3)*6];


for i=1:ndim
l{i}=sprintf('Label %02i',i);


Can this be resolved easily or am I going to have to live with not using 'DefaultFigurePosition' when I want to use gridLegend?


Comment only
08 Feb 2011 George

George (view profile)

Hi there,

Please ignore the previous rating.
This function is really useful.

The only problem that I have with it is height of the legend just stays the same size, and the color bans are proportioned.

Eg. I have 9x1 legend originally and I want a 3x3 legend after running it through the function. I want the legend to be a 3rd of the original height and 3 times the original width/length. I want the legend to be compact rather than having heaps of white space

07 Feb 2011 Adrian Cherry

Adrian Cherry (view profile)

  • 1 file
  • 3.94118

Hi Robin,

Sorry to hear that my routine has trouble with the long legend titles, I've had a quick look at it and I can see where the problem lies. It's possible to apply a quick fix it but then it messes up the short titles.

My first suggestion in the specific example you have posted is to just use the standard legend function in MATLAB, if you apply the 'orientation','horizontal' pair to legend then you'll get a one row, two column legend.

Obviously this won't help if you want a 2x2 legend with long titles. In this case for the minute you'll have to tweak the code.

At line 232

% resize the data aspect ratio to match the new shape.
set(legend_h,'dataaspectratio',[width/gd gd/numpercolumn 1]);

You'll need to tweak the aspect ratio, in your case factor the y-axis by 4.
% resize the data aspect ratio to match the new shape.
set(legend_h,'dataaspectratio',[width/gd 4*gd/numpercolumn 1]);

I'm still looking at improving the calculation so that it'll do it automatically but for the minute I hope this helps.


Comment only
14 Jan 2011 Robin Jens  
14 Jan 2011 Robin Jens

Hi Adrian

I have a problems with placing the labels in two columns when the strings are very long. As example:

y=[2 3]'*x.^2;
gridLegend(hdlY,2,{'This is the most expensive beer in the world' 'This is the most cheapest bear in the world'},'location','southoutside')

Comment only
11 Jan 2011 Matthias Pospiech

The legend gets complete messed up once I apply any property of the fonts

hLegend = gridLegend(hplot,5,{legendStr}, 'FontSize' , FontSize - 2);

here the strings are outside of the legend box all written on top of each other, and the markers are not visible.

If this would work, I would apply 5 stars!

04 Nov 2010 Riccardo

Vey useful. Thanks for sharing

02 Nov 2010 Celine Cluzel

Hi Adrian,
thanks for uploading this. Very nice combination of clickableLegend and columnlegend. Seems to work very nicely with 'plot' graphs.
I'm trying to use it for bar charts - some problems so far with color of bars changing when clicking on the legend. I will come back with a specific question once I've identified what is the problem - if any.
Thank you

13 Jan 2011

Updated to work with errorbar chart legends.

Also fixed an edge case where there is only one trace per column. It didn't like it if you had 5 traces and asked for 5 columns, it placed all the keys and labels in the first column.

Contact us