How do I edit legend position information but retain it's location within a plot?

27 views (last 30 days)
Hi Matlab fans,
I've got a problem with the size and position of my legends.
I find that the text that appears in them is frequently too large for the legend box, and spills outside of it (possibly because I favour Times New Roman font). The simple solution is to manually edit the position information of the legend handle to something more appropriate (usually by trial-and-error viewing of the result). This is fine for a one-off (e.g. a figure for publication), but I've been trying to come up with an automated way of doing this.
lg = legend ('Blah', 'Blah', 'Blah', 1);
lgpos = get(lg, 'Position');
lgpos(3) = lgpos(3) + 0.1;
set(lg, 'Position', lgpos);
However, when I edit the position information in this way, the legend's location information is deleted (i.e. set to 'none'), and though I patently use the same position information when I resize the legend box, the resulting legend is usually in a new location offset from where it was originally placed by Matlab. Amending things to something like ...
lg = legend ('Blah', 'Blah', 'Blah', 1);
lgloc = get(lg, 'Location');
lgpos = get(lg, 'Position');
lgpos(3) = lgpos(3) + 0.1;
set(lg, 'Position', lgpos);
set(lg, 'Location', lgloc);
... doesn't help either and the position information now appears overwritten (i.e. my text now spills out of the legend box again).
Does anyone have an automated solution that will allow me to both stretch my legend box to accommodate my text, while keeping the box positioned where I originally asked it to be?
Cheers,
Andrew.
P.S. I'm aware of the 'OuterPosition' information of the legend (and, in fact, now edit it in my auto-corrector script), but it seems to have no bearing on the problem here.

Answers (1)

Jan
Jan on 13 Feb 2012
The legend function has been subject to many changes in the last 10 years, therefore a helpful answer can depend on the used Matlab release.
The legend axes object is repositioned by a dedicated resize function of the figure. You can inspect the file "legend.m" to see, how this resize-function is linked to the figure size. One option is to dis-connect the original resize function and add a user-defined version. But if the units of the legend are 'normalized', most likely a disconnection is sufficient already.
There are some legend functions in the FileExchange, which are worth to try.
  1 Comment
Andrew Yool
Andrew Yool on 13 Feb 2012
Hi Jan,
Sorry - I should have added that I'm stuck in the dark ages with v2008a Matlab.
I'll give your suggestion about disconnecting the resize a shot. And I'll have a look at FileExchange - I didn't think to look there before coming to Answers.
Cheers,
Andrew.

Sign in to comment.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!