user13742363
user13742363

Reputation:

Fill in the region between two line curves in MATLAB

I need to fill the region of two lines by 'hatched grey' color. I used the following code:

M = [0.54, 0.7, 0.74, 0.78];
X1 = [0.007856, 0.008394, 0.008607, 0.012584];      %X1 values
X2 =  [0.007901, 0.008461, 0.008739, 0.011302];      %X2 values
xq = (0.54:0.000001:0.8);   %adding intervals to make line smoother
X3 = interpn(M,X1,xq,'pchip');  %other type: pchip, makima, spline etc.
X4 = interpn(M,X2,xq,'pchip');  %other type: pchip, makima, spline etc.
set(0,'defaulttextinterpreter','latex')

figure(1)
hold all; 
plot(xq, X3,'r-','LineWidth',1.5);
plot(xq, X4,'b--','LineWidth',1.5);

X=[xq,fliplr(xq)];           %create continuous x value array for plotting
Y=[X3,fliplr(X4)];           %create y values for out and then back

fill(X,Y,'g');    %plot filled area
xlabel('X','FontSize',12); % Label the x axis
ylabel('Y','FontSize',12); % Label the y axis
axis([0.5 0.8 0.007 0.013]);

However, when I tried to make the line smoother the fill in command didn't take place! I need to keep the line smoother and fill the region with a 'hatched grey' color at the same time.

Any help will be appreciated.

Upvotes: 0

Views: 111

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60444

The problem you have is that X3 and X4 contain NaN values. This happens where you attempt to extrapolate, interpn adds NaN values there.

The array xq ends at 0.8, whereas the input data, M, ends at 0.78. You should make xq end at 0.78 as well. The best way to do this is as follows:

xq = M(1):0.000001:M(end);

Though do note that the interval is very small, which leads to way too many data points to plot, it is not necessary to have this many points for a smooth plot. I suggest you use linspace instead:

xq = linspace(M(1), M(end), 1000);

Here, the 1000 is the number of points.

Upvotes: 0

Related Questions