user3074097
user3074097

Reputation: 817

How do I scale in d3.js

I want to scale some input values to some output range.

Input or Domain 10,20,40,30 ---Total Sum 100

output range should not go below 16.. and the sum of outputs of all input should be 214

myScale---d3 linear scale

var myScale = d3.scale.linear().domain([0, 100]).range([16,214]);

out1=myScale(10)
out2=myScale(20)
out3=myScale(40)
out4=myScale(30)

I want out1+out2+out3+out4 should always be equal to 214 and minimum of all the outs is 16 or greater than that.

Please let me know how can I write the scale

Upvotes: 1

Views: 140

Answers (2)

Yogesh
Yogesh

Reputation: 2228

Since the minValue is 16, and as qiu-deqing mentioned it is getting added as many times as the number of inputs, we should make sure that it is getting added only once.

var minValue = 16,
    totalSum = 214,
    numberOfInputs = 4;

var maxValue = totalSum - ((numberOfInputs - 1)*minValue);

var myScale = d3.scale.linear().domain([0, 100]).range([minValue,maxValue]);

fiddle

Upvotes: 1

qiu-deqing
qiu-deqing

Reputation: 1333

in your code, domain begin with 0 and range begin with 16

this produce a offset for each input when using scale

when you add out1 out2 out3 out4. the offset is add 4 times. so this is not what you want.

for example myScale(0 + 0 + 0 + 0 ) != myScale(0) + myScale(0) + myScale(0) + myScale(0)

we can normalize the range of scale and save the offset

var begin = 16,
    end = 214,
    range = end - begin;

var myScale = d3.scale.linear().domain([0, 100]).range([0,range]);

out1=myScale(10)
out2=myScale(20)
out3=myScale(40)
out4=myScale(30)

// maybe it is 214.000000000000003, float is not 100% accurate
console.log(begin + out1 + out2 + out3 + out4); 

demo: http://jsfiddle.net/q7WaU/

to make this solution work, you should remember to add begin for every scale to reach your

destination

Upvotes: 0

Related Questions