How can I fill between two curves, but only when one curve is above the other?
3 次查看(过去 30 天)
显示 更早的评论
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:
![Figure.png](https://www.mathworks.com/matlabcentral/answers/uploaded_files/231419/Figure.png)
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!