警告!这个答案使用无证的功能,结果在 2016a 和 2017a 版本上进行测试,其他版本可能会有所不同。
如果这也适用于其他版本的 Matlab,请在评论中告诉我。
经过一番研究后我找到了答案无证财产 http://undocumentedmatlab.com/blog/getundoc-get-undocumented-object-properties/传说中的。对于问题中的问题,最直接的答案是将图例标题的位置设置回原来的位置。这可以通过属性来完成Position
,这是hidden财产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):
如果您不介意图例会干扰数据的选项(例如您的图例位于数据轴之外),那么您可以在此停止。如果没有,请继续阅读...
我们可以将背景颜色设置为白色:
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))
上面的代码也适用于更多的单一数据系列,尽管我猜想在某些情况下这将无法给出正确的解决方案并且需要一些微调。