# Impose the color for one discrete value above a color predefined gradient

If I plot an array with option ColorFunction -> "Rainbow":

a = {{0, 1, 5, 3, 0.5, 0, 0, 2, 12, 0.50, 3, 7, 2, 0.2}};
ArrayPlot[a, PlotLegends -> Automatic, ColorFunction -> "Rainbow"]


but want the points with value = 0 (and only points with value = 0) to appear white (they are missing values) instead of purple, how should I do that? Can I specify a color for discrete points to override what ColorFunction -> "Rainbow" does?

ColorRules -> {0 -> White}


to ArrayPlot works.

Sorry I find the answer 1 min after I ask the question...

• Answering your own question is completely acceptable as long as the question and answer will be helpful for others in future. In this case, I didn't know the answer, so well done, +1. – Verbeia Mar 27 '13 at 9:37

Not all plot functions accept ColorRules, so it is good to know how to construct a custom color function anyway. For this example:

cf = If[# == 0, White, "Rainbow" ~Blend~ #] &;

ArrayPlot[a, ColorFunction -> cf]


More specified colors can be applied with Piecewise. Custom color functions can also apply to multiple dimensions:

cf = Piecewise[{
{Green, 0.2 < #2 < 0.3},
{Cyan, 0.7 < #2 < 0.8},
{Yellow, 0.2 < #1 < 0.3},
{Black, 0.7 < #1 < 0.8}
}, Blend["Rainbow", #]] &;

Plot[TriangleWave[x], {x, 0, 5},
PlotStyle -> AbsoluteThickness[5], ColorFunction -> cf, PlotPoints -> 5000]


You should also see MeshFunctions, MeshStyle, etc. for such things, which would not require such an extreme PlotPoints value, but I wished to make a point.

One could also use Lighter[] for the purpose:

ArrayPlot[a, ColorFunction -> (Lighter[ColorData["Rainbow", #], Boole[# == 0]] &)]


• Since If[# == 0, White, "Rainbow" ~Blend~ #] & is shorter, is there a reason to prefer this? – Mr.Wizard Apr 11 '13 at 12:35
• My impetus was that the Blend["Rainbow", x] construction might be unfamiliar to most. You and I know this construction, but there is no explicit mention of this thing in the docs. – J. M. will be back soon Apr 11 '13 at 12:36
• Hm... I never noticed that. +1 for documented functions! – Mr.Wizard Apr 11 '13 at 13:03
ArrayPlot[a /. 0 -> White, ColorFunction -> "Rainbow"]