# ContourPlot or DensityPlot ColorFunction with x, y and z arguments

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)

• 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. Feb 11, 2014 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. Feb 11, 2014 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] Feb 11, 2014 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. Feb 11, 2014 at 17:00

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}]
]


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