Reputation: 13
I know how to use range.js and d3.scale.linear, also know domain and range .
but when I read the code in range.js and linear.js, I was so confused that why it looks so complicated and mysterious: such as the code in linear.js:
step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)),
err = m / span * step;
// Filter ticks to get closer to the desired count.
if (err <= .15) step *= 10;
else if (err <= .35) step *= 5;
else if (err <= .75) step *= 2;
Generally,I implement the function by using "ax + b = y" ,such as:
domain(inputMin, inputMax);
stick = 4;
a = (inputMax-inputMin)/stick;
for(i = 0; i<a; i++)
{
arr[] = i*a+inputMin;
}
so why d3 use Math.log (Math.pow...) to get the 'step'?
what the code means and does?
Thanks for any help you can offer.
Upvotes: 0
Views: 119
Reputation: 11
I had to write unit tests for this algorithm last week. Here my explanation:
// Approximate the step to the closest power of ten by transforming to the
// commom log scale, truncating the mantissa, and transforming back.
step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)),
// Calculate how closely the step covers the span of the domain.
err = (m * step) / span;
// Given the coverage of the current step against the domain span, multiply
// (if necessary) by a constant to get closer to the desired tick count.
if (err <= 0.15) step *= 10;
else if (err <= 0.35) step *= 5;
else if (err <= 0.75) step *= 2;
Upvotes: 1