How can I fill between two curves, one color for when the test curve is above and a different color when it is below?

조회 수: 7 (최근 30일)
I'm hoping my aspirations for plotting aren't too ambitious for what MATLAB can handle. This is what I'm plotting right now. figure('Name','PTV'); hold on;plot(x,Base_Values.PTV{1},'--k','LineWidth',1.2);cellfun(@plot,Test_Case.PTV);
The cell Test_Case.PTV can have many elements or just one. How could I compare a plot from Test_Case.PTV to the first plot and have the area shaded red if it is above the first plot and green if below?
I would prefer to have a hatched fill, but I don't believe that's built into MATLAB, so I think I would need an outside function. But can this fill easily be done with two different colors for the corresponding areas between two curves?
And if so, I'm hoping it can be down for multiple elements at a time, although it will be quite messy, but I hope that the filled areas can be turned off with the plotted curve through plot browser. If that is not possible, I could create my function to only plot one at a time.

답변 (3개)

KSSV
KSSV 2016년 7월 8일
x = linspace(0,2*pi) ;
y = sin(x) ;
% plot(x,y) ; hold on
%%negative sine
idx1 = y<0 ;
x1 = x(idx1) ;
y1 = y(idx1) ;
x1 = [x1 x1(1)] ; % make a closed curve
y1 = [y1 y1(1)] ;
patch(x1,y1,'r','edgecolor','none') ;
% Positive sine
idx2 = y>0 ;
x2 = x(idx2) ;
y2 = y(idx2) ;
x2 = [x2 x2(1)] ; % make a closed curve
y2 = [y2 y2(1)] ;
patch(x2,y2,'g','edgecolor','none') ;
You may set 'edgecolor' option to 'none'. so that there wont be any connecting line shown.

KSSV
KSSV 2016년 6월 29일
x = linspace(0,2*pi) ;
y = sin(x) ;
plot(x,y) ; hold on
%%negative sine
idx1 = y<0 ;
x1 = x(idx1) ;
y1 = y(idx1) ;
x1 = [x1 x1(1)] ; % make a closed curve
y1 = [y1 y1(1)] ;
patch(x1,y1,'r') ;
% Positive sine
idx2 = y>0 ;
x2 = x(idx2) ;
y2 = y(idx2) ;
x2 = [x2 x2(1)] ; % make a closed curve
y2 = [y2 y2(1)] ;
patch(x2,y2,'g') ;
I hope the above example code might help you to get what you want...
  댓글 수: 5
k5jyw153vcxb
k5jyw153vcxb 2016년 7월 6일
편집: k5jyw153vcxb 2016년 7월 6일
This is what I've got so far:
figure(1)
plot(x, y1)
hold on
plot(x, y2)
%%negative sine
idx1 = y1 < y2 ;
xa = x(idx1) ;
y1a = y1(idx1);
y2a = y2(idx1);
patch([xa fliplr(xa)],[y1a fliplr(y2a)], 'r')
% Positive sine
idx2 = y1 > y2 ;
xb = x(idx2) ;
y1b = y1(idx2) ;
y2b = y2(idx2) ;
patch([xb fliplr(xb)],[y1b fliplr(y2b)], 'g')
hold off
grid
This works correctly for both regions now. I see there's a black line connecting two of my green regions that are not continuous. is there a way to get rid of this?
Star Strider
Star Strider 2016년 7월 6일
I need to have ‘x’, ‘y1’ and ‘y2’. Without them, I can’t reproduce your plot.

댓글을 달려면 로그인하십시오.


Zaka Ullah
Zaka Ullah 2021년 3월 22일
How can we draw it...

카테고리

Help CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by