# How to get varying shades of red colour based on an input value in python?

## Question:

In python, how can I get varying shades of the red/yellow colour based on an input value between -1 and 1? If the value is between -1 and 0, the function should return yellow colour.
If the value is between 0 and 1, the function should return various levels or shades of the red colour. More specifically, if the value is 0, then the colour returned should be the standard red colour #FF0000, but if it is 1, then the returned value should be vanishing light red.

My code below shows colours that are not always red (or does not appear to be red).

``````import colorsys
import matplotlib.colors as mc

if value < -1 or value > 1:
raise ValueError("Input value must be between -1 and 1")

if value <= 0:
# For values between -1 and 0, return yellow
return '#ffff00'

# Convert the input value to a hue value between 0 and 1
hue = (1 - value) / 2

# Convert the hue value to an RGB value
r, g, b = colorsys.hsv_to_rgb(hue, 1, 1)

# Convert the RGB value to a hex code
return mc.to_hex((r, g, b))
``````

I appreciate if the function returns hex code of the colour. Thank you!

With `hue = (1 - value) / 2`, it looks as though you are generating the whole range of hue values, but this is not what you want because the hue determines the color. I think you want to restrict the range so that the color gradually changes from yellow to red for positive values. You already have a proportion, so you can simply multiply by the range limit. For example, `hue = (1 - value) / 2 * 0.3` gives us:

Using colorir you can interpolate a gradient between 0 and 1

``````>>> grad = Grad(["ff0000", "fff0f0"])
"#ff0000"
"#fff0f0"
``````

Running `swatch(grad)` will print it in the terminal:

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.