How to make "rainbow" RGB values? - Python

This is a discussion on How to make "rainbow" RGB values? - Python ; Hey all, I want to map an int to a color on a rainbow spectrum, i.e. for an int n in the range 0..N, low values (near 0) should map to the red end, and high values (near N) to ...

1. How to make "rainbow" RGB values?

Hey all,
I want to map an int to a color on a rainbow spectrum, i.e. for an int
n in the range 0..N, low values (near 0) should map to the red end,
and high values (near N) to the blue/violet end.

The return values should be R, G, B tuples (well, "#xxxxxx" color
codes, but that's not the hard part.)

The trouble I'm having is in coming up with a good way to generate
color values that approximates the "ROY G BIV" rainbow spectrum. This
is just a simple, non-scientific, non-photographic application,
nothing fancy.

I've tried a simple scheme of overlapping sines, but this resulted in
too much red and blue, and no indigo/violet.

Any suggestions? I'm searching on the web now but not coming up with
much, so I thought I'd ask here.

TIA,
~Simon

Here's the sinecode I tried:

def g(n):
'''
map sine [-1.0 .. 1.0] => color byte [0 .. 255]
'''
return 255 * (n + 1) / 2.0

def f(start, stop, N):

interval = (stop - start) / N

for n in range(N):
coefficient = start + interval * n
yield g(sin(coefficient * pi))

n = 150
RED = f(0.5, 1.5, n)
GREEN = f(1.5, 3.5, n)
BLUE = f(1.5, 2.5, n)

RGBs = [('#%02x%02x%02x' % rgb) for rgb in zip(RED, GREEN, BLUE)]

2. Re: How to make "rainbow" RGB values?

>I want to map an int to a color on a rainbow spectrum, i.e. for an int
>n in the range 0..N, low values (near 0) should map to the red end,
>and high values (near N) to the blue/violet end.

[...]
>I've tried a simple scheme of overlapping sines, but this resulted in
>too much red and blue, and no indigo/violet.

Consider using an HSV->RGB conversion function. Saturation (S) and value
(V) should remain constant, while Hue (H) varies to get your rainbow
effect.

--
Andrew McNamara, Senior Developer, Object Craft
http://www.object-craft.com.au/

3. Re: How to make "rainbow" RGB values?

On Feb 24, 5:09 pm, Andrew McNamara <andr...@object-craft.com.au>
wrote:
> >I want to map an int to a color on a rainbow spectrum, i.e. for an int
> >n in the range 0..N, low values (near 0) should map to the red end,
> >and high values (near N) to the blue/violet end.

> [...]
> >I've tried a simple scheme of overlapping sines, but this resulted in
> >too much red and blue, and no indigo/violet.

>
> Consider using an HSV->RGB conversion function. Saturation (S) and value
> (V) should remain constant, while Hue (H) varies to get your rainbow
> effect.
>
> --
> Andrew McNamara, Senior Developer, Object Crafthttp://www.object-craft.com.au/

Hey thank you very much, that worked like a charm! :]

There's even a library function in the colorsys module (http://
docs.python.org/lib/module-colorsys.html)

Cheers,
~Simon