Mathias Loesch
Mathias Loesch

Reputation: 383

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!

Upvotes: 5

Views: 7118

Answers (2)

fvu
fvu

Reputation: 32953

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.

Upvotes: 4

Peaker
Peaker

Reputation: 2354

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.

Upvotes: 2

Related Questions