Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This question already has an answer here:

I want to use a different fill for a plot when the curve goes below the x-axis than when it's above that. I tried:

Plot[Sinc[x], {x, 0, 10}, PlotStyle -> Thick, Filling -> 0, 
    ColorFunction -> Function[{x, y}, If[y < 0, Red, Blue]]]

but then the whole curve has a blue filling. How should I do this?

I expected that this question has been answered before, but I couldn't find it. If it has, my apologies.

share|improve this question

marked as duplicate by bobthechemist, Dr. belisarius, Artes, Silvia, R. M. Dec 28 '13 at 18:24

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

Does this help? – bobthechemist Dec 28 '13 at 13:04
up vote 3 down vote accepted

It may be instructive to show how your attempt can be corrected. As is often(1)(2),(3),(4),(5),(6)(7)(8) the case when ColorFunction does not behave as anticipated the automatic scaling caused by ColorFunctionScaling defaulting to True is the culprit. If we set that Option to False the raw y values will be used rather than values scaled to the interval (0, 1). For better or worse this method also colors the line of the plot red or blue rather than only the fill.

Plot[Sinc[x], {x, 0, 10},
  PlotStyle -> Thick,
  Filling -> 0, 
  ColorFunction -> Function[{x, y}, If[y < 0, Red, Blue]],
  ColorFunctionScaling -> False

enter image description here

share|improve this answer
Thanks for explaining. Still, while it fixes my code, doesn't seem ideal: I can see some blue to the right of x=pi. – flup Dec 28 '13 at 13:49
@flup That's because of the sampling used; the curve is relatively straight were it crosses the axis, therefore the coloring isn't highly precise. If you use a uniform sampling it will be accurate to within the spacing of the sampling. Try with Options PlotPoints -> 500 and MaxRecursion -> 0 for example. (That's a uniform sampling of 500 points.) – Mr.Wizard Dec 28 '13 at 18:27

Here's an approach without using ColorFunction:

Plot[Sinc[x], {x, 0, 10}, PlotStyle -> Thick, Filling -> {1 -> {0, {Red, Blue}}}]

enter image description here

and I am pretty sure there are lots of similar posts, too...

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.