0

I have some python Objects with some data in them, and all of them have an id ( 1,2,3,4,5 ..... n). I have a python function where I send one of these objects and I want to plot the data from it, and the color to be different based on the id. I tried to do some things i've seen from other questions, like trying to convert the id integer into an RGB value, like this:

Blue =  integer & 255
Green = (integer >> 8) & 255
Red =   (integer >> 16) & 255

return (RED/255, Green/255, Blue/255)  # to get them into [0,1] interval

But the problem with that is that the color will be the same between close number like 1,2,3 (basicaly will have the same color almost). Any way to do this ?

EDIT:

So i was thinking of doing something like this:

def rgb_function(object_id):
    
    random.seed(object_id)
    value = random.uniform(0,1)
    #then calculate RGB value based on this answer: https://stackoverflow.com/questions/55178857/convert-a-floating-point-number-to-rgb-vector
     H = value;
     R = abs(H * 6 - 3) - 1;
     G = 2 - abs(H * 6 - 2);
     B = 2 - abs(H * 6 - 4);  
     return max(0, min(1, R)), max(0, min(1, G)), max(0, min(1, B))

     
Tenshi
  • 77
  • 2
  • 9

1 Answers1

0

You can probably get away with just shuffling a colormap with a wide variety of colors so that it gets randomized.

import random
import matplotlib.pyplot as plt
import numpy as np

colors = [plt.cm.hsv(i) for i in np.linspace(0, 1, 600)]
# random.seed(77) # uncomment this if you want the same colors everytime
random.shuffle(colors)

fig, ax = plt.subplots()
ax.plot(range(20), range(20), colors[:20]

# this gives different colors for ids that are similar

If you want truly random colors, you should see this answer. But maybe that is overkill.

krm
  • 847
  • 8
  • 13
  • Thanks for answer krm, i did something different, generating a random float between [0, 1] and then calculating the RGB value ( see my EDIT), do you think something like that is correct? – Tenshi Apr 28 '21 at 09:05
  • Your changes LGTM. This is guaranteed to generate different colors for sure. – krm Apr 28 '21 at 09:19
  • Yea, i guess another problem i would have is that sometimes the generated colors are to bright, for example there's a bright yellow color generated and when i plot the points with that color, they're kinda hard to see. Any way to lower the brightness? – Tenshi Apr 28 '21 at 09:25