1

I have a list (or np.array) of values that lie between 0 and 1, e.g.

_list = np.arange(0, 1, 0.05)
print(_list)

>>>
[0.   0.05 0.1  0.15 0.2  0.25 0.3  0.35 0.4  0.45 0.5  0.55 0.6  0.65
 0.7  0.75 0.8  0.85 0.9  0.95]

How can I map a smooth color gradient to this list, where 0 represents the color white (rgb(255,255,255)) and 1 represents the color red (rgb(255,0,0)), and all other values in between a color in between?

enter image description here

I have checked matplotlib.colors but I cannot find anything related there. I have found local topics that discuss similar things but they are all related to plotting. Am I missing something, or is it really not that trivial?

sandertjuh
  • 550
  • 2
  • 13

2 Answers2

1

Assuming that you are looking for a list of strings like rgb(255,255,255) you could use a list comprehension like this:

import numpy as np

values = np.arange(0, 1, 0.05)
print(values)
colors = [f"rgb(255, {round(v*255)}, {round(v*255)})" for v in values]
print(colors)

The output is:

[0.   0.05 0.1  0.15 0.2  0.25 0.3  0.35 0.4  0.45 0.5  0.55 0.6  0.65
 0.7  0.75 0.8  0.85 0.9  0.95]
['rgb(255, 0, 0)', 'rgb(255, 13, 13)', 'rgb(255, 26, 26)', 'rgb(255, 38, 38)', 'rgb(255, 51, 51)', 'rgb(255, 64, 64)', 'rgb(255, 77, 77)', 'rgb(255, 89, 89)', 'rgb(255, 102, 102)', 'rgb(255, 1
15, 115)', 'rgb(255, 128, 128)', 'rgb(255, 140, 140)', 'rgb(255, 153, 153)', 'rgb(255, 166, 166)', 'rgb(255, 179, 179)', 'rgb(255, 191, 191)', 'rgb(255, 204, 204)', 'rgb(255, 217, 217)', 'rgb(
255, 230, 230)', 'rgb(255, 242, 242)']
jfb
  • 45
  • 4
1

I would do it as such:

import numpy as np
_list = np.arange(0, 1, 0.05)
rgbVals = list(map(lambda x: np.subtract([255,255,255], x*np.array([0,255,255])), _list))

This Code subtracts from [255,255,255] (white) the factor from _list times [0,255,255], meaning it outputs [255,0,0] if the element is 1 or [255,255,255] if the element is 0.

Kenny
  • 530
  • 3
  • 12