图例标题在 MatLab 上不起作用

legend title do not work on MatLab

我试图在我的 matlab 代码中为我的图例函数添加一个标题,但它不起作用。我在他们的网站上使用 MatLab 官方帮助,但它没有改变任何东西。

我的代码:

stem(100,300,'blue', 'Marker', '*', 'MarkerSize', 4,'LineStyle', '-');
hold on
stem(80,500,'green', 'Marker', '*', 'MarkerSize', 4,'LineStyle', '-');
hold on
stem(30,1400,'red', 'Marker', '*', 'MarkerSize', 4,'LineStyle', '-');
axis([0 150 0 2000]);
hold off
lgd=legend('100%','80%','30%','Location','northeastoutside');
**title(lgd,'My Legend Title','FontSize',12);**
xlabel('DoD(%)','fontname','times','fontsize',16);
ylabel('Number of cycles','fontname','times','fontsize',16);

我从 Matlab 站点获取了这段代码

x = -pi:pi/20:pi;
y1 = sin(x);
plot(x,y1)

hold on
y2 = cos(x);
plot(x,y2)
hold off

lgd = legend('sin(x)','cos(x)');
**title(lgd,'My Legend Title')**

但剧情还是没有改变什么。

我找到了适用于早期版本 Matlab 的解决方案。

我想 il_raffa 是正确的 - Matlab 2016a 及更高版本支持为 legend 设置 title(我认为)。

从这里下载 legendTitlehttp://www.mathworks.com/matlabcentral/fileexchange/48331-add-a-title-to-a-legend

您可以使用以下代码示例:

stem(100,300,'blue', 'Marker', '*', 'MarkerSize', 4,'LineStyle', '-');
hold on
stem(80,500,'green', 'Marker', '*', 'MarkerSize', 4,'LineStyle', '-');
hold on
stem(30,1400,'red', 'Marker', '*', 'MarkerSize', 4,'LineStyle', '-');
axis([0 150 0 2000]);
hold off
lgd=legend('100%','80%','30%','Location','northeastoutside');

xlabel('DoD(%)','fontname','times','fontsize',16);
ylabel('Number of cycles','fontname','times','fontsize',16);

if verLessThan('matlab', '9.0')
    %Before Matalb 2016a, use legendTitle (downloaded from MathWorks file exchange).
    set(lgd, 'Position', get(lgd, 'Position').*[1, 0.9, 1, 1]);
    legendTitle(lgd, 'My Legend Title','FontSize',12);
else
    %Matalb 2016a and above, use title (built in function).
    title(lgd,'My Legend Title','FontSize',12);
end

Matlab 2016a:


Matlab 2014b:


Matlab 2012b:

你可以试试这个:

set(get(lgd,'Title'),'String','My Legend Title')