Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.data skipping the first row of data

Tags:

d3.js

I have the following code that works great, except when I iterate through my data set, the first row (the 0 index) is getting skipped.

svg.selectAll("rect")
  .data(data)
  .enter()
  .append("rect")
  .attr("x",function(d){
    console.log(data);
    console.log(d);
    return xScale(d.year-1980);
  })

Note the console.log(data) returns my full data set, including the first row so the data is there!

But console.log(d) shows all rows after and including my second row of data - it drops the first row.

Any suggestions are welcome.

like image 435
user2846817 Avatar asked Oct 04 '13 13:10

user2846817


2 Answers

I had the same issue with similar code, and fixed it based on Lars Kothoff's comment.

In my case it made sense to change the selectAll to work on a g element, more like so:

svg.selectAll("g")
    .data(data);
    .enter()
    .append("g")
    .append("rect")
    .attr("x",function(d) { return xScale(d.year-1980); });

You could also differentiate the rects with a class:

svg.selectAll("rect.year")
    .data(data)
    .enter()
    .append("rect")
    .attr("x",function(d){ return xScale(d.year-1980); })
    .classed("year");
like image 194
James Manley Avatar answered Nov 18 '22 12:11

James Manley


Yeah, it seems if there is already an element, it gets "skipped" by the .enter()

<html>
<head>

<title>D3 Test</title>
</head>

<body>

</body>

<script type='text/javascript' src='https://d3js.org/d3.v4.min.js'></script>
<script type='text/javascript'> 

var theData = ["James", "Sue", "Ben"]

var p = d3.select("body").selectAll("p")    
    .data(theData)
    .enter()
    .append('p')
    .text(function (d,i) {
      return " i =" + i + "data =" + d;
    });

</script>

</html>

Produces

i =0data =James

i =1data =Sue

i =2data =Ben

But if you add a p element in there, it'll skip it.

...[previous code]

<body>
<p>Here is the first p tag that "James gets matched too"</p>

</body>

...[previous code]
like image 2
James Holland Avatar answered Nov 18 '22 12:11

James Holland