Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
600 views
in Technique[技术] by (71.8m points)

d3.js - d3.data skipping the first row of data

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...