简体   繁体   中英

How to map an array of integers to a color shade in NodeJS?

What is the best way to map an array of integers to a color range? I have an array:

count = [ '290', '11', '8', '8', '6', '6', '3', '3', '3', '3' ]

Which i want to map to shades of red ranging from rgb(255, 0, 0) to rgb(255, 255, 255).

Currently i am just mapping the integers in the array to 0-255 with this function from here :

const scale = (num, in_min, in_max, out_min, out_max) => { return (num - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; }

var count = [ '290', '11', '8', '8', '6', '6', '3', '3', '3', '3' ]
var count_last = count[count.length - 1];
var count_first = count[0];
var new_count  = []
count.forEach(function(entry) {
  new_count.push(Math.round(scale(entry, count_last, count_first, 255, 0)))
})`

Output:

[ 0, 248, 251, 251, 252, 252, 255, 255, 255, 255 ]

This works, but with this example the value 290 would be red, and all the other values nearly white so you cant distinguish them, although 11 for example is much bigger than 3. Is there some other way with which i can dynamically map the integers to shades of red or do i have to hard code thresholds at which the color will change?

if i understood you correctly, you are interested in linear mapping of one range of numbers to other range of numbers. mathematically speaking, you are interested in bijective function from [a,b] to [c,d] .

you would like to use it in order to map a range of integers (it implies that you know the range of the input) into a shade of red where the red color span in the ranger of [0,255] (256 shades of red, which is the range of the output)

thus, assuming that the range of your input (based on the minimum and maximum in the count array) is [3,290] and the range of the output is [0,255] then when you feed the value 3 from the input to the mapping function, it should return 0. same goes for the value 290 from the input, which is mapped to 255 in the output. so if M(x) is a mapping function, we have:

M(3) = 0
M(290) = 255

we have 2 points in hand (3,0) and (290,255). by euclidean geometry : any two distinct points, there is a unique line containing them; and the plot is achived by

f(x) = f'(x)(x-x_0) + y_0

where

f'(x) = (y_1 - y_2) / (x_1 - x_2)

in your case, it is

M(x) = (255 - 0) / (290 - 3) * (x - 3) + 0

where x belongs to the ranger of your input, which in this case is [3,290]

note that , if the two ranges are of different sizes, some values might overlap depending on the quantization of the mapping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM