Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Is it possible to apply a color function to ContourPlot or DensityPlot that is function of x, y and z, and not simply of z?

Example:

ContourPlot[Cos[x] + Cos[y], {x, 0, 4 Pi}, {y, 0, 4 Pi}, 
 ColorFunction -> (If[#1 > 1/2, Red, White] &)]

but colored only for x > 2 Pi (obviously, there are alternative methods for this example, but typical cases are more complex)

share|improve this question
    
Not if the docs are correct. ContourPlot appears to pass only a single value. You could try to generate the contours and the background colour separately, then combine them together to achieve the effect. –  Szabolcs Feb 11 at 16:53
    
@Szabolcs on this case it is easy, for others, only by doing a ContourPlot that outputs the color value on z, and then use it as backbroud, which is clearly a non optimum solution. –  P. Fonseca Feb 11 at 16:55
    
This is not going to be of as good a quality as ContourPlot, and it's again just a hack: DensityPlot[(x - 2 Pi) Sign[Cos[x] + Cos[y]], {x, 0, 4 Pi}, {y, 0, 4 Pi}, MeshFunctions -> {Function[{x, y}, Cos[x] + Cos[y]]}, Mesh -> 5, PlotPoints -> 100, ColorFunction -> "RedBlueTones", Exclusions -> None] –  Szabolcs Feb 11 at 16:57
    
The colouring and the contours are treated separately by specifying one as "the function to plot" and the other as "mesh functions". Instead of using mesh function, you could generate the contour lines with ContourPlot for better quality, then combine with Show. –  Szabolcs Feb 11 at 17:00
add comment

1 Answer

up vote 6 down vote accepted

The problem is that ColorFunction receives only one parameter, the value of the function, when called by ContourPlot. This is explained in the details of the documentation. A crude way to see that would be printing the argument received by ColorFunction :

ContourPlot[Cos[x] + Cos[y], {x, 0, 4 Pi}, {y, 0, 4 Pi}
 , ColorFunction -> 
  Function[{x, y, z}, Print[{x, y, z}]; If[x > 1/2, Red, White]]]

So I guess the answer is no, if you want to use ColorFunction on ContourPlot.

Another solution could be to superimpose your ContourPlot into a RegionPlot or another graphic function that would provide {x,y} to the ColorFunction:

Show[
 RegionPlot[
  Cos[x] + Cos[y] > 0 && 2 x > y, {x, 0, 4 Pi}, {y, 0, 4 Pi}, 
  ColorFunction -> Function[{x, y}, Hue[y]]],
 ContourPlot[
  Cos[x] + Cos[y] == Range[-2, 2, 0.25], {x, 0, 4 Pi}, {y, 0, 4 Pi}]
 ]

enter image description here

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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