AndreyIto
AndreyIto

Reputation: 974

D3Js.v5: ...selectAll(...).data(...).enter is not a function

I'm learning D3 JS, and I'm trying to replicate the D3 bar chart tutorial here. It works as is using d3.v3, but the moment I change the src to d3.d5 by changing:

<!DOCTYPE html>
<meta charset="utf-8">
<style>
//Irrelevant CSS...
</style>
<svg class="chart"></svg>

<script src="https://d3js.org/d3.v5.min.js"></script> //Changed to d3.v5
<script>

var width = 420,
    barHeight = 20;

var x = d3.scale.linear()
    .range([0, width]);

var chart = d3.select(".chart")
    .attr("width", width);

d3.tsv("data.tsv", type, function(error, data) {
  x.domain([0, d3.max(data, function(d) { return d.value; })]);

  chart.attr("height", barHeight * data.length);

  var bar = chart.selectAll("g")
      .data(data)
    .enter().append("g")
      .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

  bar.append("rect")
      .attr("width", function(d) { return x(d.value); })
      .attr("height", barHeight - 1);

  bar.append("text")
      .attr("x", function(d) { return x(d.value) - 3; })
      .attr("y", barHeight / 2)
      .attr("dy", ".35em")
      .text(function(d) { return d.value; });
});

function type(d) {
  d.value = +d.value; // coerce to number
  return d;
}

</script>

I get an error:

Uncaught (in promise) TypeError: chart.selectAll(...).data(...).enter is not a function

I'd rather learn the latest and greatest, which I assume is D3.v5, instead of D3.v3, unless the latter really is the latest stable build. Was there a syntax change in this method chain? because I thought .selectAll(...).data(...).enter would be a pretty "standard" method chain. This has been surprisingly resistant to googling, unfortunately; similar problems are much more complex use-cases with many more degrees of freedom, whereas my question simply involves changing the D3 version.

Upvotes: 4

Views: 5791

Answers (1)

AB9KT
AB9KT

Reputation: 121

I see 2 problems with your solution:

  1. Change d3.scale.linear() to d3.scaleLinear()
  2. Change d3.tsv("data.tsv", type, function(error, data) { to d3.tsv("data.tsv").then(function(data) {

Explanation for 2: d3.tsv function returns a promise which needs to be resolved before you can use the data

Upvotes: 2

Related Questions