# ListDensityPlot controlling the number of colors

Is there a way to set the number of colors used in ListDensityPlot. I am using "Rainbow" as follows:

ShowLegend[
ListDensityPlot[TestList, ColorFunction -> "Rainbow"],
{ColorData["Rainbow"][1 - #1] &, 10,
ToString[LMax], ToString[LMin], LegendPosition -> {1.1, -.4}}]


TestList is a list like {{x1,y1,z1},{x2,y2,z2},...}

In the Legend, to get 5 colors, I can change the 10 above to 5, and I get 5 colors. I would like to do the same in ListDensityPlot as well and get 5 colors. Can someone tell me how to do this?

Thanks. Shrihari

-

You can use ListContourPlot confining the contours and you can keep a higher interpolation order:

data = Table[Sin[j^2 + i], {i, 0, Pi, Pi/25}, {j, 0, Pi, Pi/25}];

ListContourPlot[data, Contours -> 3, ColorFunction -> "Rainbow"]


-
And then there's that. (facepalm) +1 – Mr.Wizard Jul 31 '13 at 15:23
:) your formidable reputation record made me re-read the question a couple of times in case I had misunderstood it... – gpap Jul 31 '13 at 15:29
Even the best make mistakes. So, I figure I have to make some too if I aspire to greatness. :^) – Mr.Wizard Jul 31 '13 at 18:36
Thanks @gpap for the suggestion to use ListContourPlot instead. That gives a better looking plot. – Shrihari Aug 1 '13 at 10:08
However, in ListContourPlot, I get different number of contours for what I think are two equivalent ways of doing it: (1) use the Contours->9 option, (2) Contours->{c1,c2,...c9} where ci are equally spaced. I get 10 colors in (1) as it should, but only 5 colors in (2). Am I missing something? – Shrihari Aug 1 '13 at 10:11

To get a limited number of colors you can Round the values given to the ColorFunction.
With Round[#, 1/3] there will be four values: {0, 1/3, 2/3, 1}.

To keep these colors from being blended between regions may require that you don't use interpolation, i.e. set InterpolationOrder -> 0. (Or you could do it the right way -- see gpap's answer.)

data = Table[Sin[j^2 + i], {i, 0, Pi, Pi/25}, {j, 0, Pi, Pi/25}];

ListDensityPlot[data,
InterpolationOrder -> 0,
ColorFunction -> (Blend["Rainbow", Round[#, 1/3]] &)
]


-
Thanks, Mr.Wizard. I got this to work too, but as you suggest, went with the "right way". – Shrihari Aug 1 '13 at 10:19