Search code examples
matlabplotcurveregionshading

MATLAB Shading region between SEVERAL curves


There are many questions already on this site for something similar:

MATLAB, Filling in the area between two sets of data, lines in one figure

MATLAB fill area between lines

However, all of the existing questions relate to two curves only. How do you fill a region bounded by several curves that overlap each other?

A crude example would be:

% Create sample data as column vectors.
x = [1 : 100]';
curve1 = x/10;
curve2 = log(x/2) + rand(length(x), 1) - 0.5;
curve3 = log(x) + rand(length(x), 1) + 0.5;
% Plot it.
plot(x, curve1, 'r', 'LineWidth', 2);
hold on;
plot(x, curve2, 'b', 'LineWidth', 2);
plot(x, curve3, 'k', 'LineWidth', 2);

For the shading: The upper limit would be the black curve followed by the red line.

The lower limit would be the blue curve (briefly), then the red line, followed by the blue curve.

In my actual dataset I have 10 curves which require a similar thing.


Solution

  • If I understand you correctly, you can do this by creating a min and max vectors of the area you want to shade, and use flipud to shade the region with fill

    min_data=min([curve1,curve2,curve3],[],2);
    max_data=max([curve1,curve2,curve3],[],2);
    
    fill([x;flipud(x)],[min_data;flipud(max_data)],'g')
    

    enter image description here