Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

An example

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.

[Related: Change the colour scheme in DensityPlots to make the zero white]

share|improve this question

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]]
share|improve this answer
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

Your Answer


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.