Generate distinctly different RGB colors in graphs

前端 未结 12 1270
故里飘歌
故里飘歌 2020-11-30 16:51

When generating graphs and showing different sets of data it usually a good idea to difference the sets by color. So one line is red and the next is green and so on. The pro

12条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 17:33

    You could also think of the color space as all combinations of three numbers from 0 to 255, inclusive. That's the base-255 representation of a number between 0 and 255^3, forced to have three decimal places (add zeros on to the end if need be.)

    So to generate x number of colors, you'd calculate x evenly spaced percentages, 0 to 100. Get numbers by multiplying those percentages by 255^3, convert those numbers to base 255, and add zeros as previously mentioned.

    Base conversion algorithm, for reference (in pseudocode that's quite close to C#):

    int num = (number to convert);
    int baseConvert = (desired base, 255 in this case);
    (array of ints) nums = new (array of ints);
    int x = num;
    double digits = Math.Log(num, baseConvert); //or ln(num) / ln(baseConvert)
    int numDigits = (digits - Math.Ceiling(digits) == 0 ? (int)(digits + 1) : (int)Math.Ceiling(digits)); //go up one if it turns out even
    for (int i = 0; i < numDigits; i++)
    {
      int toAdd = ((int)Math.Floor(x / Math.Pow((double)convertBase, (double)(numDigits - i - 1))));
      //Formula for 0th digit: d = num / (convertBase^(numDigits - 1))
      //Then subtract (d * convertBase^(numDigits - 1)) from the num and continue
      nums.Add(toAdd);
      x -= toAdd * (int)Math.Pow((double)convertBase, (double)(numDigits - i - 1));
    }
    return nums;
    

    You might also have to do something to bring the range in a little bit, to avoid having white and black, if you want. Those numbers aren't actually a smooth color scale, but they'll generate separate colors if you don't have too many.

    This question has more on base conversion in .NET.

提交回复
热议问题