How can I fill between two curves, but only when one curve is above the other?
조회 수: 3 (최근 30일)
이전 댓글 표시
Luciano Campos
2019년 7월 26일
답변: Vinicius Pereira Mateus Borges
2019년 7월 26일
Hello,
I'd like to fill the gap between two lines, but only when one line is above the other.
With the data file attached and the command:
plot(x,y1,'k',x,y2,'k:');
hold on;
xlim([x(1) x(end)]);
jbfill(x',y1',y2',[.8 .8 .8],'none',0,.5);
legend('y1','y2');
hold off;
I can plot:
which always fills the gap between y1 and y2. But I'd like it to be filled only when y1>y2.
Any help on this is very welcome.
Best,
댓글 수: 0
채택된 답변
Alex Mcaulley
2019년 7월 26일
You can do a little trick:
plot(x,y1,'k',x,y2,'k:');
hold on;
xlim([x(1) x(end)]);
y1tmp = y1;
y1tmp(y1<y2) = y2(y1<y2);
jbfill(x',y1tmp',y2',[.8 .8 .8],'none',0,.5);
legend('y1','y2');
hold off;
추가 답변 (2개)
KSSV
2019년 7월 26일
load Data.mat ;
plot(x,y1,'k',x,y2,'k:');
hold on;
xlim([x(1) x(end)]);
% jbfill(x',y1',y2',[.8 .8 .8],'none',0,.5);
legend('y1','y2');
hold off;
idx = y1>y2 ;
figure
X = [x(idx) ; flipud(x(idx))] ;
Y = [y1(idx) ; flipud(y2(idx))] ;
fill(X,Y,'r')
댓글 수: 0
Vinicius Pereira Mateus Borges
2019년 7월 26일
Hi, I am new to MATLAB - I just started doing an online course a few weeks ago - so this is probably not a very good solution.
But it works!
plot(x,y1,'k',x,y2,'k:');
hold on;
xlim([x(1) x(end)]);
% initiate temporary variable
temp1 = zeros(1,numel(x));
temp2 = zeros(1,numel(x));
for i = 1:numel(x)
if y1(i) > y2(i)
temp1(i) = y1(i) % only store values of y1 if y1>y2
temp2(i) = y2(i) % only store values of y2 if y1>y2
end
end
jbfill(x',temp1,temp2,[.8 .8 .8],'none',0,.5); % only plot values when y1>y2
legend('y1','y2');
hold off;
shg
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!