Colored gradient fill under curve

조회 수: 20 (최근 30일)
Leo
Leo 2020년 6월 27일
댓글: Leo 2020년 10월 27일
I know this is not the most elegant solution, but it works. Indeed, I am a beginner, so excuse me. My question is, how to simplify it all?
Here's what I want to achieve: I have a 2D plot and I want to make a gradient fill under curve. From one specific color to transparent. I tried to use white instead of transparent, but I want the grid to be visible. So I'm little lost here.
Did some search and I looked for some examples here and tried to modify them. So, this is an edited code that worked to fill a specific range. I spread it all over the axis. I also didn't want to fill the gradient over the edge of the curve, so I had to insert plot again. Yeah, that's not ideal at all, but as I said, it's working.
I believe that this can be done more easily. Could you advise me, please?
% Input data
x = 0:0.01:10*pi;
y1 = sin(x)+9;
y2 = repmat(5,length(y1),1);
figure1 = figure;
plot(x,y1);
grid on;
hold on;
% Fill the whole area - 0-31.4
val = [0,31.4];
for i = 1:2;
tmp = abs(x-val(i));
[~,idx(i)] = min(tmp);
end
id = idx(1):1:idx(2);
x2 = x(id);
y1a = y1(id);
y2a = y2(id);
y2a = y2a';
X=[x2,fliplr(x2)];
Y=[y1a,fliplr(y2a)];
% I set the transparency and removed borders.
% This is a workaround, I don't want to set the whole transparency.
h = fill(X,Y,Y,'LineStyle','none');
set(h,'facealpha',.5)
% Here is how I made the gradient between red and white.
% This is not very nice solution and I would like to simplify it.
% Of course, color bar is not visible.
set(gca,'Colormap',[1 1 1; '...a lot of data...' ;1 0 0]);
% Need to plot again because of overlaping
plot(x,y1);
Preview of plot

채택된 답변

darova
darova 2020년 6월 28일
Use alphaData property, set facealpha to interp
x = 0:0.2:10;
y = sin(x)+10;
xx = [x;x];
yy = [y;y*0];
surf(xx,yy,xx*0,...
'alphadata',yy,...
'facealpha','interp',...
'edgecolor','none');
line([0 x x(end) 0],[0 y 0 0],'linew',2)
view(2)
  댓글 수: 1
Leo
Leo 2020년 10월 27일
I have also a related question: Is there any option how to set a different Alim for multiple surf plots? For example I have surf1 with height 20, another surf2 with height 10. Unfortunately gradient for both starts from the highest number 20 so I'm unable set it for each separately.
x = 0:0.1:50;
y = 5*sin(x)+5;
y2 = 5*sin(x+5)+15;
xx = [x;x];
yy = [y;y*0];
yy2 = [y2;y2*0];
Color1 = [0.72 0.28 1];
Color2 = [0 0.45 0.74];
figure
alim([0 max(y)]); % NOT WORKING!
s1=surf(xx,yy,xx*0,...
'alphadata',yy,...
'facealpha','interp',...
'edgecolor','none',...
"FaceColor",Color1);
hold on
alim([0 max(y2)]); % NOT WORKING!
s2=surf(xx,yy2,xx*0,...
'alphadata',yy2,...
'facealpha','interp',...
'edgecolor','none',...
"FaceColor",Color2);
view(2)

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Surface and Mesh Plots에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by