How to convert a number to a color from green to red?

Question:

I have a task.
With a Python script, I need to generate a table with values and do what is called "conditional formatting" in Excel. Depending on the value, I need to make the background green, yellow or red. But not just by the threshold values, but by the gradient. The larger the number, the redder the cell.

Is there any library that will allow me to set the min and max value, the current value and get a color on the gradient in return?

I tried to search myself, but I don’t fully understand how to properly google it.

Here is an example from excel:
enter image description here

I would like a function. Something like
num_co_color(min_value, max_value, current_value) which, when passed to a function, would return the color in RGB.

Asked By: Kucherov Egor

||

Answers:

You can do it yourself simply enough. Decide your minimum and maximum values, then set:

p = (value - min) / (max - min)
Green = 255 * (1 - p)
Red   = 255 * p
Blue  = 0

So, substituting in some trial values… if value = min, p will be 0, and you’ll get G=255 and R=0.

If value = max, p will be 1, and you’ll get G=0 and R=255.

Elsewhere you’ll get a linear mixture.

Answered By: Mark Setchell
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.