viernes, 9 de enero de 2015

Color gradation for reports (from red to green)

A little piece of code I wrote to represent a color gradation: red means very bad, green very good and everything in between. The trick here is to use HSV system instead of RGB. You keep the S and V to your favourite value and change the H from 0 to 120 degrees. Here is the function:


import colorsys

def get_color (percentage):

    V=1.0
    S=0.6
    H= (float(percentage) * 120.0) / 36000.0 

    R, G, B = colorsys.hsv_to_rgb (H, S, V)

    R = int (R * 255.0)
    G = int (G * 255.0)
    B = int (B * 255.0)

    octets = [R, G, B]

    color = "#{0:02X}{1:02X}{2:02X}".format (*octets)  

    return  color