# DensityPlot colours symmetric around zero

I have some function of two variables (which happens to be the error in some approximation I'm interested in). I'd like to get a density plot of the function, such that in regions when the function is zero, the plot is white, and then there is shading in two different colours when it is positive or negative. Here is an example of what I'd like to get. When the range is not symmetric around zero, by default zero no longer corresponds to white. It's not too hard to fix this case-by-case, by looking at what the range of the function is and changing the ColorFunction accordingly:

ColorFunction -> (ColorData["RedGreenSplit", .5 + #/myScaling] &), ColorFunctionScaling -> False

But this requires that I first somehow work out what value of myScaling to plug in manually each time. It would be nice to be able to do this automatically: get Mathematica to do what it usually does with ColorFunctionScaling, but with the constraint that the chosen range is centred at 0.

## 1 Answer

You can get a color gradient that is symmetric around zero using a custom Blend as the ColorFunction, plus ColorFunctionScaling -> False.

DensityPlot[x + y , {x, -2, 2}, {y, -3, 2},
ColorFunction -> (Blend[{{-5, Green}, {0, White}, {4, Red}}, #] &),
ColorFunctionScaling -> False]


Knowing the minimum and maximum of the data range is probably best handled as a custom function along the lines of the following:

niceDensityPlot[f_, {xmin_, xmax_}, {ymin_, ymax_}, color1_: Green,
color2_: Red] /; xmin < 0 && xmax > 0 && ymin < 0 && ymax > 0 :=
With[{zmin = FindMinValue[f[x, y], {{x, 0}, {y, 0}}],
zmax = FindMaxValue[{f[x, y], x >= xmin, x <= xmax, y >= ymin,
y <= ymax}, {{x, 0}, {y, 0}}] },
DensityPlot[f[x, y] , {x, xmin, xmax}, {y, ymin, ymax},
ColorFunction -> (Blend[{{zmin, color1}, {0, White}, {zmax,
color2}}, #] &), ColorFunctionScaling -> False]]

• Thanks for the answer. (Though I guess NMaxValue rather than FindMaxValue is a better choice, since it finds a global, not local, maximum). – Holographer Apr 22 '15 at 17:18
• I have to admit I didn't test the function extensively. Glad I could help! By the way, according to the documentation, NMaxValue etc also only find local minima, unless f is linear. – Verbeia Apr 22 '15 at 22:39