Gajus
Gajus

Reputation: 73838

How to make the scale to round to the nearest multiple of #?

x.scale = d3.time.scale().domain(x.extent).range([0, dimensions.graph.width]);

This code uses x.extent ([Wed Aug 01 2012 00:00:00 GMT+0300 (EEST), Tue Aug 07 2012 00:00:00 GMT+0300 (EEST)]) and graph width (1000) to generate x value scale. However, I need this value to be rounded to the nearest multiple of 25 (Math.round(x/25)*25).

By doing this I want to achieve exact width ticks that are now defined as:

x.axis = d3.svg.axis()
    .ticks(d3.time.days, 1)
    .tickSize(10, 5, 0)
    .scale(x.scale);

How to extend x.scale to round to the nearest multiple of 25?

Upvotes: 6

Views: 6327

Answers (3)

amd
amd

Reputation: 21462

The correct answer is interpolateRound, from the docs

Returns an interpolator between the two numbers a and b; the interpolator is similar to interpolateNumber, except it will round the resulting value to the nearest integer.

var xScale = d3.scaleLinear()
    .domain([0, 100])
    .range([0, width])
    .interpolate(d3.interpolateRound); // <-- round interpolation

Upvotes: 6

EoghanM
EoghanM

Reputation: 26944

Are you looking for the nice function?

x.scale = d3.time.scale().domain(x.extent)
            .range([0, dimensions.graph.width]).nice();

Upvotes: 5

Josh
Josh

Reputation: 5480

perhaps I am misunderstanding, but couldn't you just transform the result as you suggested after applying the scale function? ie:

function roundScale(origVal) { return Math.round(x.scale(origVal)/25) * 25;}

then use that value to set attributes:

.attr("x", function(d) { return roundScale(d.value); }

Upvotes: 1

Related Questions