MATLAB:如何向任何绘图添加自定义图例

MATLAB:如何向任何绘图添加自定义图例,matlab,matlab-figure,Matlab,Matlab Figure,如何将自定义图例添加到任何绘图? 例如: figure(200) plot(t1:k,Pexact(t1:k,1),'-xk'); plot(t1:k,xh(1,t1:k),'-sr'); 然后我想用同样的代码来添加绘图 hold on plot(t1:k,xh(1,t1:k),'-sb'); 然后我想为所有三个情节添加一个图例 if exist('hl','var') clear hl end hold on hl(1) = plot(t1,0,'-sr'); hl(2) = plot(t

如何将自定义图例添加到任何绘图?
例如:

figure(200)
plot(t1:k,Pexact(t1:k,1),'-xk');
plot(t1:k,xh(1,t1:k),'-sr');
然后我想用同样的代码来添加绘图

hold on plot(t1:k,xh(1,t1:k),'-sb');
然后我想为所有三个情节添加一个图例

if exist('hl','var')
clear hl
end
hold on
hl(1) = plot(t1,0,'-sr');
hl(2) = plot(t1,0,'-sb');
hl(3) = plot(t1,0,'-xk');
set(hl,'LineWidth',2);
set(hl,'Visible','off');
legend(hl,'SC-PF','PF','Truth',...
    'Location','NorthWest');
  • 注:将0,0更改为原始绘图中存在的x,y坐标

我更喜欢在调用绘图时定义图例。如果某个特定集合中缺少数据,或者设置了条件,因此并非每次都绘制所有数据,则此方法更有意义

figure(fig)
hold on
plot(t1:k,Pexact(t1:k,1),'-xk','DisplayName','SC-PF');
plot(t1:k,xh(1,t1:k),'-sr','DisplayName','PF');
plot(t1:k,xh(1,t1:k),'-sb','DisplayName','Truth')
legend(get(fig, 'Child'),'show')
legend('location','northwest')