作者:faaronzheng 转载请注明出处!
Matlab创建一个Legend非常简单,但是当创建两个甚至多个的时候就会遇到很多麻烦。接下来我们就介绍一下如何在Matlab中创建多个Legend。
%--------------------------------------plot
c1=plot(r1app(:, 1), r1app(:, 2), 'g.'); %r1app(:, 1) r1app(:, 2)都是矩阵
hold on;
c2=plot(r1test(:,1),r1test(:,2),'+g');
hold on;
% l1=legend('class1:train', 'class1:test',1);
% set(l1,'Orientation','horizon');
c3=plot(r2app(:, 1), r2app(:, 2), 'r.');
hold on;
c4=plot(r2test(:,1),r2test(:,2),'+r');
hold on;
c5=plot(r3app(:, 1), r3app(:, 2), 'b.');
hold on
c6=plot(r3test(:,1),r3test(:,2),'+b');
hold on;
%----------------------------------------Legend
%--------------------------------------method 1
%legend('class1:train','class1:test','class2:train','class2:test','class3:train','class3:test');
%--------------------------------------method 2
[legh,objh,outh,outm]=legend(c1,'class1:train');
set(legh,'Box','off');
set(legh,'position',[0.2,0.8,0.1,0.1]);
legh2=copyobj(legh,gcf);
[legh2,objh2]=legend(c2,'class1:test');
set(legh2,'Box','off');
set(legh2,'position',[0.4,0.8,0.1,0.1]);
legh3=copyobj(legh2,gcf);
[legh3,objh3,outh3,outm3]=legend(c3,'class2:train');
set(legh3,'Box','off');
set(legh3,'position',[0.2,0.75,0.1,0.1]);
legh4=copyobj(legh3,gcf);
[legh4,objh4]=legend(c4,'class2:test');
set(legh4,'Box','off');
set(legh4,'position',[0.4,0.75,0.1,0.1]);
legh5=copyobj(legh4,gcf);
[legh5,objh5,outh5,outm5]=legend(c5,'class3:train');
set(legh5,'Box','off');
set(legh5,'position',[0.2,0.7,0.1,0.1]);
legh6=copyobj(legh5,gcf);
[legh6,objh6]=legend(c6,'class3:test');
set(legh6,'Box','off');
set(legh6,'position',[0.4,0.7,0.1,0.1]);
代码如上每一个Legend下面第一个set是用来取消Legend边框的,第二个set是固定Legend的位置,因为去掉边框后就不能用鼠标拖动Legend了,所以必须通过代码来设定Legend的位置。一定要记得在除第一个外每个Legend下使用copyobj()函数;不然会覆盖之前的Legend。
用method1产生的效果如下!
用method2产生的效果如下!
第二种是不是明显比第一种好看多了~~而且使用第二种方法可以创建任意多个Legend。
也可以参考我的百度经验:Matlab如何创建多个Legend