4

I'm trying to shade the area above a constant horizontal line. Above the horizontal line represents data in the top 10% (i.e., 90% of my data is below the horizontal line). I used the function (curve intersect) to find the start and end of where the horizontal line intersects my data. But, I cannot figure out how to plot the area above the horizontal line, constrained by the curve. Does anyone know how to do this in Matlab? An example of my attempt is provided in the figures attached. Thank you!

Fig. 1: Black line is my horizontal constant line. The red circles represent the 'curveintersect' start and end points. I tried to plot the data to fill in the red line, but it's capturing data below the 10% line.

Black line is my horizontal constant line. The red circles represent the 'curveintersect' start and end points. I tried to plot the data to fill in the red line, but it's capturing data below the 10% line.

Fig. 2. I also attempted to use the fill function, but again, I'm capturing data outside the blue curve.

I also attempted to use the fill function, but again, I'm capturing data outside the blue curve.

Example code related to figure 2 was adopted from here (http://blogs.mathworks.com/graphics/2015/10/13/fill-between/):

mask = y2 > y1; %find where blue curve is greater than the horizontal 90th % line 
fx = [x(mask), fliplr(x(mask))];
fy = [y1(mask), fliplr(y2(mask))];
hold on
fill_color = [.929 .694 .125];
fh = fill(fx,fy,fill_color);
hold off

I have repeated the area function for 3 subplots, each with the same code, just different variables:

area(x, max(y, min(x)), min(x), 'EdgeColor','none','FaceColor', [.7 .7 .7]); alpha(.3);

The first subplot (orange stippled line) isn't plotting, but the 2nd and 3rd subplots are.

enter image description here

user3052817
  • 245
  • 3
  • 9

1 Answers1

8

Use area as follows:

x = 0:.01:4*pi;  %// x data
y = sin(x);      %// y data
level = 0.5;     %// level
plot(x, y)
hold on
area(x, max(y, level), level, 'EdgeColor', 'none', 'FaceColor', [.7 .7 .7])

enter image description here

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • I tried it out and it worked for one of my plots, however, when I used your code for a second plot, it doesn't show the shaded area. I tested it, and when I assign a color to 'EdgeColor', I see the area it should fill but no color is shaded in. Do you know why that may be? – user3052817 Nov 17 '15 at 22:36
  • @user3052817 No idea. Can you post a minimal example? – Luis Mendo Nov 18 '15 at 00:59
  • It's hard to tell without seeing the actual code or values that reproduce the problem. Is `min(x)` the correct level? Can it be that it's above the whole graph in the orange case? – Luis Mendo Nov 18 '15 at 07:22
  • I figured it out. It was because the last data point in the variable was a NaN value. Once I removed it, the area function plotted perfectly. – user3052817 Nov 18 '15 at 17:51