How does the d3.scaleBand work?

Nafis picture Nafis · Jul 23, 2016 · Viewed 24.9k times · Source

How can I make the line var x = d3.scale.ordinal().rangeRoundBands([0, width], .05); from this example work in d3 v4 using d3.scaleBand?

Answer

Gerardo Furtado picture Gerardo Furtado · Jul 23, 2016

in D3 4.x, ordinal.rangeRoundBands has been replaced with band.rangeRound (thus, there is no more rangeRoundBands). Besides that...

The new band.padding, band.paddingInner and band.paddingOuter methods replace the optional arguments to ordinal.rangeBands.

So, that 0.05 goes to paddingInner. This is how the line looks in D3 v4.x:

d3.scaleBand()
    .rangeRound([0, width])
    .paddingInner(0.05);

I have rewritten the code in your example, updated to D3 v4.x: https://plnkr.co/edit/HQz1BL9SECFIsQ5bG8qb?p=preview

Necessary changes:

  • var parseDate = d3.timeParse("%Y-%m");
  • var x = d3.scaleBand().rangeRound([0, width]).paddingInner(0.05);
  • var y = d3.scaleLinear().range([height, 0]);
  • var xAxis = d3.axisBottom(x).tickFormat(d3.timeFormat("%Y-%m"));
  • var yAxis = d3.axisLeft(y).ticks(10);
  • for the bars: .attr("width", x.bandwidth())