Monday, 17 June 2019

Use scales to remap a number

I have a domain of numbers, for example domain = [100, 200] and a number of bands in which to divide the range, for example bands = 5. I know that each band corresponds to a value:

band #1 --> v = 0.2
band #2 --> v = 0.4
band #3 --> v = 0.6
band #4 --> v = 0.8
band #5 --> v = 1.0

These values are fixed (hard coded): if bands became bands = 6 then is the developer that choose what is the value of band #6.

I want to divide the domain into bands whose size varies according to the scale used. For example I might want to use either the linear or the logarithmic or the pow scale.

Then I want a function that in input takes a number x ∈ domain and must return the value v associated with the band to which the inout number belongs.

Here a similar question, but now I want to use different scales (for example I can use d3 scales) but I don't know how..

Here a piece of code:

function getLinearScaledValue(x, min, max, bands) {
  const range = max - min
  if (x === max) {
    return 1
  } else {
    return Math.floor(1 + ((x - min) / range) * bands) / bands
  }
}

where min and max are the min and max value of the domain.

I think sleepwalking's examples was good so I put them here:

if bands = 5:

band #1 --> v = 0.2
band #2 --> v = 0.4
band #3 --> v = 0.6
band #4 --> v = 0.8
band #5 --> v = 1.0

(1) if scale is linear and domain = [0, 100] --> bands are:

band #1 --> v = 0.2 --> [0, 20]
band #2 --> v = 0.4 --> [21, 40]
band #3 --> v = 0.6 --> [41, 60]
band #4 --> v = 0.8 --> [61, 80]
band #5 --> v = 1.0 --> [81, 100]

for example:

if x = 0  --> v = 0.2
if x = 10 --> v = 0.2
if x = 21 --> v = 0.4
if x = 98 --> v = 1.0

(2) if scale is linear and domain = [100, 200] --> bands are:

band #1 --> v = 0.2 --> [100, 120]
band #2 --> v = 0.4 --> [121, 140]
band #3 --> v = 0.6 --> [141, 160]
band #4 --> v = 0.8 --> [161, 180]
band #5 --> v = 1.0 --> [181, 200]

for example:

if x = 100 --> v = 0.2
if x = 110 --> v = 0.2
if x = 121 --> v = 0.4
if x = 198 --> v = 1.0

(3) if scale is logarithmic and domain = [0, 100] --> bands are:

band #1 --> v = 0.2 --> [?, ?]
band #2 --> v = 0.4 --> [?, ?]
band #3 --> v = 0.6 --> [?, ?]
band #4 --> v = 0.8 --> [?, ?]
band #5 --> v = 1.0 --> [?, ?]

for example:

if x = 0  --> v = ?
if x = 10 --> v = ?
if x = 21 --> v = ?
if x = 98 --> v = ?



from Use scales to remap a number

No comments:

Post a Comment