我在一个图中有10条曲线,但它们中只有三条应出现在图例中。例如,在10条曲线中,只有第一个,第五个和第十个应该在图例中,我该怎么做?
这是我的计划:
x=1:0.5:15;
y1=x.^1
plot(x,y1)
hold on
y2=x.^1.2
plot(x,y2)
hold on
.
.
.
y10=x.^2.2
plot(x,y10)
答案 0 :(得分:8)
您可以使用图形的手柄,然后通过其手柄指定图例的图形:
x=1:0.5:15;
y(1,:)=x.^1;
y(2,:)=x.^1.2;
...
...
...
y(10,:)=x.^2.2;
for k=1:10
h(k)=plot(x,y(k,:));
hold on
end
legend([h(1) h(5) h(10)],'curve 1','curve 5','curve 10');
hold off
答案 1 :(得分:1)
您需要使用图例功能中的绘图控制柄来指示所需的曲线。在您的代码中插入它看起来像这样:
x=1:0.5:15;
y1=x.^1;
h1=plot(x,y1,'r');
hold on
y2=x.^1.2;
h2=plot(x,y2,'c');
hold on
.
.
.
y10=x.^2.2;
h10=plot(x,y10,'p');
hold off;
legend([h2,h10] , 'Fart 2', 'More Fart'); % Plot in the handle you wish
答案 2 :(得分:1)
legend
可以使用句柄或句柄,以及字符串列表。我冒昧地重写你的代码,所以它在循环中绘制而不是创建一堆y
变量。一般来说,如果你发现自己创建了一系列名为y1,y2等的变量,那么在MATLAB中有一种更好的方法。
有7个地块,而不是10个,但你明白了。
x=1:0.5:15;
m=1:0.2:2.2;
figure
hold on
for n = 1:7
h(n) = plot(x,x.^m(n));
end
legend(h([1,3,5]),'Plot One', 'Plot Three', 'Plot Five',...
'Location', 'NorthWest')
答案 3 :(得分:0)
legend
命令仅适用于最近创建的绘图,除非传递句柄。
figure
for c=1:10
subplot(4,4,c)
ezplot('y=sin(x)');
if c==5||c==10
legend('sin(x)')
end
end
答案 4 :(得分:0)
这是我使用的光滑双线:
a=flipud(findall(gcf,'Type','Line')); %get all line objects of current plot
legend(a([1 3]),{'a','b'}) %add legend for line 1 and 3, 'a' and 'b'