Setting a title for a legend in Matlab

The following code is the most Minimal, complete, and testable example I can 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')

It leads to:

legend name

As you can clearly see, something is wrong with the title of the top legend. One way or another, a request for a attlegend output interferes with its "header". Firstly, for some reason it makes it invisible, but this is already allowed in the code above.

The main problem is its position - it does not have such a property, so after installation I can not move it.

Matlab, (, text ), , . , , .

Matlab 2016a.

+4
1

! , 2016a 2017a .
, Matlab.


. - . Position, NodeChildren, .

, . , :

[hleg,att] = legend('show');
title(hleg,'my title')
hleg.Title.NodeChildren.Position

ans =
     0     0     0

. :

hleg.Title.NodeChildren.Position = [0.5 1.5 0];

(x = 0,5) (y = 1,5), , (z = 0):

right place

, , (, ), . , ...


:

hleg.Title.NodeChildren.BackgroundColor = 'w';

, . , , . ( ), :

x = 1:0.1:10;
plot(x,sin(x),x,cos(x))
[hleg,icons,plots] = legend('show');
title(hleg,'my title')
hleg.Title.Visible = 'on';
% the addition in height needed for the title:
title_hight = hleg.Position(4)/numel(plots);
hleg.Position([2 4]) = [hleg.Position(2)-title_hight hleg.Position(4)+title_hight];
% calculate new position for the elements in the legeng:
new_pos = fliplr(0.5/(numel(plots)+1):1/(numel(plots)+1):1);
hleg.Title.NodeChildren.Position = [0.5 new_pos(1) 0];
% set the text to the right position:
leg_txt = findobj(icons,'Type','Text');
txt_pos = cell2mat({leg_txt.Position}.');
txt_pos(:,2) = new_pos(2:end);
set(leg_txt,{'Position'},mat2cell(txt_pos,[1 1],3));
% set the icons to the right position:
leg_att = findobj(icons,'Type','Line');
set(leg_att,{'YData'},mat2cell(repmat(repelem(new_pos(2:end).',...
    numel(plots)),1,2),ones(numel(plots)*2,1),2))

, , , .

big box

+1
source

Source: https://habr.com/ru/post/1669638/


All Articles