Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Map float range [0.0, 1.0] to color range [red, green]?

I have a function that returns float results in the interval [0.0, 1.0]. I would like to visualize the results using color ranging from red for 0.0 to green for 1.0 (maybe through yellow for 0.5). How could I do that? Thanks!

like image 799
Mathias Loesch Avatar asked Jul 12 '11 07:07

Mathias Loesch


2 Answers

I think the simplest way is to work in HSL/HSB (hue saturation lightness), where the hue values 0-33% of the maximum will map to the range red-orange-yellow-green. The advantage of working is HSL (vs RGB) is that the resulting color range will be much better-looking (eg bright yellow in RGB contains a pinch of blue).

So basically you will create a value based on a constant S and L value, and a H that corresponds to

your_value * (1/3 of the maximum H value, often 255)

and then transform that value back to RGB for display. Don't know Python (shame on me) but apparently the colorsys module can do this transformation for you.

like image 110
fvu Avatar answered Nov 03 '22 05:11

fvu


Assuming you have a way to present RGB values represented as 3-tuples (R,G,B) in the range of 0..1, it sounds like you want to go from: (1, 0, 0) to: (0, 1, 0).

You can just use: rgbs = [(1-i,i,0) for i in your_floats]

Then use any graphics library to visualize these 3-tuples as actual RGB colors.

like image 21
Peaker Avatar answered Nov 03 '22 05:11

Peaker