一、仅标注部分曲线的图例
用法:在legend函数中指定需要标注的曲线及图例标签
clear;
clc;
x=linspace(0,2*pi,100);
y1=sin(x);
y2=sin(x+pi/4);
y3=sin(x+pi/2);
figure
h1=plot(x,y1,'r');
hold on
h2=plot(x,y2,'b');
hold on
h3=plot(x,y3,'g');
grid on
legend([h1 h3],'y1','y3');
效果:仅标注了曲线y1和y3的图例
二、画图后显示/隐藏曲线
用法:利用legend属性的ItemHitFcn回调,点击图例时执行自定义回调函数
clear;
clc;
x=linspace(0,2*pi,100);
y1=sin(x);
y2=sin(x+pi/4);
y3=sin(x+pi/2);
figure
h1=plot(x,y1,'r');
hold on
h2=plot(x,y2,'b');
hold on
h3=plot(x,y3,'g');
grid on
hobj=legend('y1','y2','y3');
hobj.ItemHitFcn=@HitCallbackFcn;
function HitCallbackFcn(src,evnt) % 当点击图例后执行的自定义函数
if strcmp(evnt.Peer.Visible,'on')
evnt.Peer.Visible = 'off';
else
evnt.Peer.Visible = 'on';
end
end
效果:点击图例中的y2后,曲线y2隐藏;再次点击图例y2,曲线y2显示