How to shade the area between two lines (constructed by large number of data points)
55 views (last 30 days)
Show older comments
I have seen some examples in which mostly MATLABer's have used curve1 and curve2 as an equation. and then using the flip method they shaded the required area between these two curves.
In my case I don't have any equation but a large number of data points. by using simple plot(xdata,ydata) I am ploting these lines. Now my question is how can I shade the areas between two or three lines drawn by plot command.
Accepted Answer
Star Strider
on 27 May 2023
It works the same way with data points as with functions —
x = linspace(0, 10, 50).'; % Assume Column Vectors
y1 = rand(size(x));
y2 = rand(size(x))+1;
y3 = rand(size(x))+2;
figure
plot(x, y1)
hold on
plot(x, y2)
patch([x; flip(x)], [y1; flip(y2)], 'r', 'EdgeColor','none', 'FaceAlpha',0.5)
patch([x; flip(x)], [y2; flip(y3)], 'g', 'EdgeColor','none', 'FaceAlpha',0.5)
hold off
grid
Most MATLAB data are column vectors, so I am using that convention here. For row vectors, replace the semicolons (;) with commas (,) in the patch calls.
Note that the independent variable vector (‘x’ here) must be monotonically increasing (or decreasing) for patch to work correctly. It cannot be random. If it is random, create a matrix and then sort it:
A = [x(:) y1(:) y2(:)];
As = sortrows(A,1);
xs = As(:,1);
y1s = As(:,2);
y2s = As(:,s);
Then use the sorted vectors as the patch arguments.
.
2 Comments
More Answers (1)
See Also
Categories
Find more on NaNs in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!