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?


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)

  • $\begingroup$ 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. $\endgroup$
    – Szabolcs
    Feb 11, 2014 at 16:53
  • $\begingroup$ @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. $\endgroup$
    – P. Fonseca
    Feb 11, 2014 at 16:55
  • $\begingroup$ 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] $\endgroup$
    – Szabolcs
    Feb 11, 2014 at 16:57
  • $\begingroup$ 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. $\endgroup$
    – Szabolcs
    Feb 11, 2014 at 17:00

1 Answer 1


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:

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

enter image description here

  • $\begingroup$ Are there any other solutions? It is so strange that ContourPlot can use ColorFunction with z argument only. $\endgroup$ May 30, 2020 at 13:03

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.