Setting a title for a legend
Afficher commentaires plus anciens
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.
Réponse acceptée
Plus de réponses (2)
Kelly Kearney
le 14 Fév 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 commentaire
Eyal Ben-Hur
le 15 Fév 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").
Catégories
En savoir plus sur Legend dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

