fill underneath a curve with a gradient fill

matlab, plot

Solution

Method One

Here we will need the the handle of the patch created by fill the simplest way would be to change the last line to

Hpatch = fill(X,Y,'b'); 

Then we can set the colour data to be based on the y values and set the face colour to be interpolated

cdata=get(Hpatch,'ydata');
cdata=(cdata-min(cdata))/(max(cdata)-min(cdata)); %// normalise
set(Hpatch,'CData',cdata,'FaceColor','interp')

The three lines above get the ydata of the patch, normalise it, then set it to be the colour data of the patch and set the shading to interpolated. The jet color map is default but to ensure jet is used add the line `colormap('jet')` after the code above.

note: normalising is optional as it will be automatically normalised however I personally would prefer to control it myself especially if handling multiple objects.

Output

Method Two

More simply, but less instructive, let Matlab do it for you, you can set the colour to be based on Y in the call to fill: `fill(X,Y,Y)`

Problem

I can fill an area underneath a specific part of a curve as follows: ``` x = 0:0.01:2*pi; y1 = sin(x)+10; y2 = repmat(5,length(y1),1); plot(x,y1); hold on; % fill area between 1 and 2 val = [1,2]; 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)]; fill(X,Y,'b'); ``` Is it possible, however, to use a gradient fill instead of a solid color? It would be great, for example, to use a jet colormap instead. Is this possible?

Original source