0

I have a variabble ranging from -10 to 10 and constantly changing. I want to have a python function returning RGBA values:

Red: when close to -10,
Green: when close to 10

I can't think of a way to do this myself and I suppose someone has done something like that in the past.

  • 2
    You need to linearly interpolate between the two colors. See my answers to the question [Range values to pseudocolor](https://stackoverflow.com/questions/10901085/range-values-to-pseudocolor). – martineau Feb 11 '21 at 19:06
  • Does this answer your question? [Range values to pseudocolor](https://stackoverflow.com/questions/10901085/range-values-to-pseudocolor) – maij Feb 12 '21 at 07:47

2 Answers2

2

You can use a color representation like HSV to do this. You can take your rgb color max (255, 0, 0) and min (0, 255, 0) and convert those to HSV (0, 100%, 100%) (120, 100%, 100%). Looking at these you can see that only one value changes, the hue. So you can map your range -10:10 to the range of the hue 0:120. This can be done using a pretty simple mapping function:

def map_values(oldValue):
    # this is your range -10:10
    OldRange = (10 - -10)
    # range we are mapping to 0:120
    NewRange = (120 - 0)
    return (((oldValue - -10) * NewRange) / OldRange) + 0

Now that you have a hue, you can convert that into an RGB value. There is a handy function for this in colorsys

import colorsys
# we need to divide by 360 because this function
# expects a value from 0.0 to 1.0. H has a range from 0 to 360
my_rgb_color = colorsys.hsv_to_rgb(map_values(your_value) / 360.0, 1.0, 1.0)
eric556
  • 115
  • 5
1

Instead of importing a module, you can use this function:

def rg(num):
    num = 255 * num // 10
    if num > 0:
        return 255 - num, 255, 0
    return 255, 255 + num, 0

print(rg(-10), rg(0), rg(10))

Output:

(255, 0, 0) (255, 255, 0) (0, 255, 0)
Red
  • 26,798
  • 7
  • 36
  • 58