12
$\begingroup$

I would like to have a plot that is filled to the axis with Green if the y value is greater than 10, and Blue if it is less than 10.

I attempted to do the following:

Plot[x, {x, 0, 20}, Filling -> Axis, ColorFunction -> Function[{x, y}, Piecewise[{{Green, y > 10}, {Blue, y < 10}}]]]

The produces an all blue filling.

The frustrating thing is that it seems that conditionals are allowed in ColorFunctions, but the test is evaluated only once, and the result is evaluation for each point plotted.

How can I have the test evaluated repeatedly to get a discrete color filling?

Note: I am simply trying to fill the space under a curve by determining where a point would fall in a given set of intervals.

$\endgroup$
2
  • $\begingroup$ Incidentally your code can be simplified: ColorFunction -> (If[#2 > 10, Green, Blue] &) $\endgroup$
    – Mr.Wizard
    Commented Jun 13, 2012 at 11:44
  • $\begingroup$ In the code that I am actually using, there are 5 intervals, so I just removed some, and changed the numbers for the piecewise function. $\endgroup$
    – soandos
    Commented Jun 13, 2012 at 16:47

2 Answers 2

8
$\begingroup$

ParametricPlot with MeshFunctions + MeshShading +Mesh options gives a cleaner picture with no blending of colors at boundaries:

ParametricPlot[{x, v x}, {x, 0, 20}, {v, 0, 1}, 
 MeshFunctions -> {# &}, Mesh -> {{10}}, 
 MeshShading -> {Blue, Green}, BoundaryStyle -> None]

enter image description here

You can color more complicated regions:

ParametricPlot[{x, v x}, {x, 0, 20}, {v, 0, 1}, 
 MeshFunctions -> {# Sin[RandomReal[5] + #] &}, Mesh -> {{0}}, 
 MeshShading -> {Hue[RandomReal[]], Hue[RandomReal[]]}, 
 BoundaryStyle -> None]

enter image description here

$\endgroup$
15
$\begingroup$

The problem is not that the test is only evaluated once but that by default ColorFunctionScaling is set to True which means that the coordinates are rescaled to lie in the interval $[0,1]$ before being fed to ColorFunction. Try this instead

Plot[x, {x, 0, 20}, Filling -> Axis, 
 ColorFunction -> Function[{x, y}, Piecewise[{{Green, y > 10}, {Blue, y < 10}}]],
 ColorFunctionScaling -> False]

Mathematica graphics

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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