MATLAB: Hatchfill certain area under curve: findobj

areacurvehatchhatched patcheshatchfill2

Hi,
I was wondering how to get the area left to the line where the mean is hatched in color using hatchfill2 function:
x = [-3:.1:3];
norm = normpdf(x,0,1);
figure;
plot(x,norm)
y1 = get(gca,'ylim');
hold on
plot([mean(norm) mean(norm)],y1)
I am aware this tutorial, however, I already struggle getting the right area with findobj.
Thanks in advance!

Best Answer

You plotted the mean as a line instead of as a patch. The hatchfill and hatchfill2 File Exchange contributions require patch objects.
nmean = mean(norm);
on_left_side = x <= nmean;
left_x = x(on_left_side);
left_y = norm(on_left_side);
patch_x = [left_x(:); left_x(end); left_x(1)];
patch_y = [left_y(:); left_y(1); left_y(1)];
h = patch(patch_x, patch_y, 'w');
hatchfill(h);
If you look carefully at the result before doing the hatch fill you will note that the patch created might end slightly to the left of the line. This has to do with the fact that your x is quantized by your colon operator so the mean can fall between two x values.
I considered posting code to do the interpolation so you got a good edge match, but I did not bother working it out, because your line is fundamentally meaningless. norm is your y coordinate and you are taking the mean over that y coordinate, and you are then turning that mean y coordinate into an x coordinate. It would make a lot more sense if you were drawing a horizontal line and hatching above or below it.
Related Question