pythonmatplotlibgraphcolorsrgb

# How to create an RGB rainbow gradient in Python 2.7?

I looked at Generating color gradient in Python, but it's not doing the trick.

I usually create random RGB values for coloring figures but I want to create an RGB gradient in between a particular range. In this case, the range would from 0 to 307, where 0 would be the darkest red in RGB and 307 would be the highest frequency violet in RGB.

With the help from King Arthur below, I've used this code to get it from darkest red to ultra violet but no rainbow colors in between. I'm looking to output a list of n values (307 in this case) of RGB hex colors spanning the colors of the rainbow, so I can plot them in matplotlib.

``````def hex_to_RGB(hex):
''' "#FFFFFF" -> [255,255,255] '''
# Pass 16 to the integer function for change of base
return [int(hex[i:i+2], 16) for i in range(1,6,2)]

''' returns a gradient list of (n) colors between
two hex colors. start_hex and finish_hex
should be the full six-digit color string,
inlcuding the number sign ("#FFFFFF") '''
# Starting and ending colors in RGB form
s = hex_to_RGB(start_hex)
f = hex_to_RGB(finish_hex)
# Initilize a list of the output colors with the starting color
RGB_list = [s]
# Calcuate a color at each evenly spaced value of t from 1 to n
for t in range(1, n):
# Interpolate RGB vector for color at the current value of t
curr_vector = [int(s[j] + (float(t)/(n-1))*(f[j]-s[j])) for j in range(3)]
# Add it to our list of output colors
RGB_list.append(curr_vector)
return RGB_list

start = '#660000'
end = '#7f1ae5'.upper()
``````

Solution

• Found the answer with `colorsys` http://python3.codes/fractal-tree/

The goods are here:

``````# https://docs.python.org/2/library/colorsys.html
(r, g, b) = colorsys.hsv_to_rgb(hue, 1.0, 1.0)
R, G, B = int(255 * r), int(255 * g), int(255 * b)
``````

Argument `hue` must be from 0.0 to 1.0.