tags:

views:

75

answers:

2

What would be the easiest way to lightly shade (or hatch; or anything to set it different from the rest) an area in a plot(), below a curve y=x^2, for example ?

x = 0:pi/10:2*pi;  
y = x.^2.;
plot(x,y);
+5  A: 

area(x,y) should do the trick. I'm not sure if that class has a FaceAlpha property though.

EDIT: Unfortunately, the area class doesn't have a FaceAlpha property. But you can work around that and edit the patch directly:

x=0:pi/10:2*pi;
y=x.^2;
H=area(x,y);
h=get(H,'children');
set(h,'FaceAlpha',0.5); %#Tada!

EDIT2: To shade the area above the curve, you could use a second area plot with a white fill. It's kind of a kludge, but it should work. Starting over:

x=0:pi/10:2*pi;
y=x.^2;
y2=max(y)*ones(size(y));
hold on
H1=area(x,y2);
H2=area(x,y);
set(H2,'FaceColor',[1 1 1]);
axis tight

or building on Jason S's solution, use the baseval input to shade above the curve:

x=0:pi/10:2*pi;
y=x.^2;
baseval=max(y);
H=area(x,y,baseval);
h=get(H,'children');
set(h,'FaceAlpha',0.5,'FaceColor',[0 1 0]);
axis tight
Doresoom
I'm still getting used to matlab's ways, so excuse if this simple question. But where do you set the color in those 3 lines ? And how for example would you shade an area above the curve with that principle ?
ldigas
Accepting it nevertheless ...
ldigas
shade area above the curve: no need to kludge. See my answer.
Jason S
@Jason S: good point. I didn't know you could set baseval above the points in the curve! +1
Doresoom
Instead of setting FaceAlpha on the child patch, you could set FaceColor directly on the area handle. It would not be transparent but you can achieve the same light shade.
Yair Altman
@Yair Altman: True, I wrote my answer under the assumption that there were other curves/points/etc plotted on the same axis.
Doresoom
+3  A: 

A supplemental example to elaborate on Doresoom's post:

x=0:pi/50:2*pi;
y1=x.^2;
y2=10+5*sin(3*x);
baseval1=20;
baseval2=3;
clf;
hold on;
H1=area(x,y1,baseval1);
H2=area(x,y2,baseval2);
hold off;
h=get(H1,'children');
set(h,'FaceAlpha',0.5,'FaceColor',[1 0.5 0]);
  % set color to orange, alpha to 0.5
h=get(H2,'children');
set(h,'FaceAlpha',0.5,'FaceColor',[0.85 1 0.25]);
  % set color to yellow-green, alpha to 0.5

But where do you set the color ?

h is a handle to a patch (a filled in area); if you type get(h) you can see all its properties. The MATLAB docs on patch properties explain these to some degree.

And how for example would you shade an area above the curve with that principle ?

area creates a patch between a base value and a curve. Doesn't look like there's an easy way to create an area between two curves though.

Jason S

related questions