Generate distinctly different RGB colors in graphs

前端 未结 12 1265
故里飘歌
故里飘歌 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:42

    There's a flaw in the previous RGB solutions. They don't take advantage of the whole color space since they use a color value and 0 for the channels:

    #006600
    #330000
    #FF00FF
    

    Instead they should be using all the possible color values to generate mixed colors that can have up to 3 different values across the color channels:

    #336600
    #FF0066
    #33FF66
    

    Using the full color space you can generate more distinct colors. For example, if you have 4 values per channel, then 4*4*4=64 colors can be generated. With the other scheme, only 4*7+1=29 colors can be generated.

    If you want N colors, then the number of values per channel required is: ceil(cube_root(N))

    With that, you can then determine the possible (0-255 range) values (python):

    max = 255
    segs = int(num**(Decimal("1.0")/3))
    step = int(max/segs)
    p = [(i*step) for i in xrange(segs)]
    values = [max]
    values.extend(p)
    

    Then you can iterate over the RGB colors (this is not recommended):

    total = 0
    for red in values:
      for green in values:
        for blue in values:
          if total <= N:
            print color(red, green, blue)
          total += 1
    

    Nested loops will work, but are not recommended since it will favor the blue channel and the resulting colors will not have enough red (N will most likely be less than the number of all possible color values).

    You can create a better algorithm for the loops where each channel is treated equally and more distinct color values are favored over small ones.

    I have a solution, but didn't want to post it since it isn't the easiest to understand or efficient. But, you can view the solution if you really want to.

    Here is a sample of 64 generated colors: 64 colors

提交回复
热议问题