D3 4.0 rangeRoundBands equivalent?

Javascriptd3.js

Javascript Problem Overview


I see a lot of D3 code that has something like this:

var x = d3.scale.ordinal()
  .rangeRoundBands([0, width], .1);

As of D3 version 4.0 d3.scale.ordinal() is now d3.scaleOrdinal and rangeRoundBands seems to be gone.

> d3.scaleOrdinal()

{ 
  [Function: scale]
  domain: [Function],
  range: [Function],
  unknown: [Function],
  copy: [Function] 
}

What would the D3 v4 equivalent of this code (from Mike Bostock's bar chart example) be?

var x = d3.scale.ordinal()
  .rangeRoundBands([0, width], .1);

Javascript Solutions


Solution 1 - Javascript

In D3 4.x rangeRoundBands was moved to the new Band scale:

d3.scaleBand()
    .range([range])
    .round([round]);

That's equivalent to:

d3.scaleBand()
    .rangeRound([range]);

Here is the API: https://github.com/d3/d3-scale#band-scales

Solution 2 - Javascript

var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);

The above calculates bands and sets padding between band. In v4, the equivalent is

var x = d3.scaleBand()
    .rangeRound([0, width])
    .padding(0.1);

Solution 3 - Javascript

var svg = d3.select("svg"),

margin = {top: 20, right: 20, bottom: 30, left: 60},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;

var x = d3.scaleBand().rangeRound([0, width]).padding(0.1),
    y = d3.scaleLinear().rangeRound([height, 0]);

var g = svg.append("g")
   .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

d3.tsv("data.txt", function(d) {
  d.y = +d.y;
  return d;
}, function(error, data) {
  if (error) throw error;

  x.domain(data.map(function(d) { return d.x; }));
  y.domain([0, d3.max(data, function(d) { return d.y; })]);

A launchable syntax for a classic chart using both scaleBand and scaleLinear.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmikewilliamsonView Question on Stackoverflow
Solution 1 - JavascriptGerardo FurtadoView Answer on Stackoverflow
Solution 2 - JavascriptNan ZhouView Answer on Stackoverflow
Solution 3 - Javascript因特网的小熊View Answer on Stackoverflow