How pick colors for a pie-chart?

codeguru picture codeguru · Oct 25, 2008 · Viewed 50.4k times · Source

I have some code that generates image of a pie chart. It's a general purpose class, so any number of slices can be given as input. Now I have problem picking good colors for the slices. Is there some algorithm that is good at that?

Or maybe I should just hand-pick and list fixed colors? But how many. Maybe 10 colors and hope there will not be more than 10 slices ever? Also, which 10 colors to pick?

Colors need to follow some rules:

  • they need to look nice
  • adjacent colors should not be similar (blue next to green is a no-go)
  • pie background color is white, so white is out of option

Some algorithm manipulating with RGB values would be a preferred solution.

Answer

Niels Bosma picture Niels Bosma · Apr 13, 2011

I solved it as follows:

  1. Choose a base color.
  2. Calculate its hue (baseHue).
  3. Create a color with the same saturation and luminosity, with its hue calculated as:
      hue = baseHue + ((240 / pieces) * piece % 240
    

In C#:

int n = 12;

Color baseColor = System.Drawing.ColorTranslator.FromHtml("#8A56E2");
double baseHue = (new HSLColor(baseColor)).Hue;

List<Color> colors = new List<Color>();
colors.Add(baseColor);

double step = (240.0 / (double)n);

for (int i = 1; i < n; ++i)
{
    HSLColor nextColor = new HSLColor(baseColor);
    nextColor.Hue = (baseHue + step * ((double)i)) % 240.0;
    colors.Add((Color)nextColor);
}

string colors = string.Join(",", colors.Select(e => e.Name.Substring(2)).ToArray());

I used the HSLColor class.

The Google Charts example that uses 12 pieces and a base color of #8A56E2:

Chart Example