File Exchange

image thumbnail


version 1.0 (3.48 KB) by

Shrinks the length of the legend lines.



View License

**Matlab no longer allows access to the elements within a legend, so this code will not work from Matlab circa-2014 onwards.**
legendshrink reduces the amount of horizontal space taken up by a figure legend by reducing the length of lines. (Best results when the legend box is off.)

This is important for small plots because the size of the lines is
constant irrespective of the physical size of the figure. Only works
for vertical legends, for now.

Comments and Ratings (8)



I wrote a similar function that also broke with the new Matlab release. In order to fix your function, you just need to remove the call to the legend handle to retrieve the 'Children':

lch = get(lg,'Children'); %(get rid of this)

With the new Matlab behavior, you no longer need the 'Children', you can just go straight into the legend object handle to get the legend objects. In other words, instead of:

cch = findobj(lch,'-not','Tag','legendlabel');

you can use:

[l,lobj] = legend; (this would be done by the user and then lobj would be passed to the function)
cch = findobj(lobj,'-not','Tag','legendlabel');

I have not tried to fix your function based on the similarity with my function (not published) I think my fix will work or at least help you out.

Thanks for letting me know. Matlab no longer appears to allow getting access to the lines inside of a legend -- e.g., writing the following results in an empty array:

h = legend;
hch = get(h,'children')

Given this, I don't think it's possible to "shrink" a Matlab legend any more :( You'd have to write entirely new code to draw a legend manually.

It seems the code doesn't work for 2014b. Is there any plan to modify the code?

Adam Danz

Adam Danz (view profile)

Thanks for the code. I have a vertical legend in the upper right corner with two elements within the legend. The code is shrinking one of the elements as described but upon the second loop, I get the following error:

Error using hg.hggroup/get
The name 'XData' is not an accessible property for an instance of class 'hggroup'.
Error in legendshrink (line 114)
linepos = get(cch(ii),'XData');


Excellent. Thanks for the script.

Works nicely (when used with legend box off), but unfortunately it does not work when printing a figure. With print preview, the legend is set back to the way it looks without legendshrink.

Leo Simon

I'd prefer to leave the legend box on. Is there any way of shrinking the box as you shrink the lines?


Ross (view profile)

Excellent little script. Did exactly what I needed it to do for a small figure.



Matlab no longer allows access to the elements within a legend, so this code will not work from Matlab circa-2014 onwards.

MATLAB Release
MATLAB 8.2 (R2013b)
Tags Add Tags

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video