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.
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");
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With