Setting a title for a legend
Show older comments
The following code is the most minimal example that I could find. My true case is much more complicated:
x = 1:0.1:10;
y = sin(x);
subplot 211
plot(x,y)
[leg,att] = legend('show');
title(leg,'my title')
leg.Title.Visible = 'on';
subplot 212
plot(x,y)
leg = legend('show');
title(leg,'my title')
This results in:

As you can clearly see, something is wrong with the upper legend title. Somehow, asking for the att output of the legend interfere with its' title. First, for some reason, it makes it invisible, but that is already solved in the code above.
The main problem is with its position - it doesn't seem to have such a property, so once set I can't move it.
I can think of some similar hacks by myself (like using text with the position of the legend), but my situation is very complicated, and I already configure the legend a lot and have several axes in every figure. Thus, I prefer a simple and working solution that rely on the original functionality of the legend title.
I use Matlab 2016a.
Accepted Answer
More Answers (2)
Kelly Kearney
on 14 Feb 2017
As a workaround, legendflex.m should handle this fine. With this option, you can include the second output from the legend call.
I don't currently include the title handle as output (I should correct that), but you can grab it via findall to format as desired:
x = 1:0.1:10;
y = sin(x);
subplot 211
plot(x,y)
[leg,att] = legendflex(gca, {'data 1'}, 'title', 'my title');
set(findall(leg, 'string', 'my title'), 'fontweight', 'bold');
leg.Title.Visible = 'on';
subplot 212
plot(x,y)
leg = legendflex(gca, {'data 2'}, 'title', 'my title');
set(findall(leg, 'string', 'my title'), 'fontweight', 'bold');

1 Comment
Eyal Ben-Hur
on 15 Feb 2017
If you limit yourself to one output from the legend command, then the title is positioned correctly...as you noted in your original question.
x = 1:0.1:10;
y = sin(x);
subplot 211
plot(x,y)
leg = legend('show'); % Just one output here
title(leg,'my title')
subplot 212
plot(x,y)
leg = legend('show');
title(leg,'my title')
If you need the other outputs from legend, then the documentation offers a workaround using legend properties (see "Returning multiple outputs is not recommended").
Categories
Find more on Legend in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
