简体   繁体   中英

Binding data in d3 appends too many times

I have an array of 3 JSON objects that I want to bind in d3 to make some rectangles. However, instead of just going through the array once, it goes through it multiple times. I was wondering if this code looks wrong.

var w = 5000;
var h = 5000;
var svg = d3.select("body")
         .append("svg")
     .attr("width", w)   
     .attr("height", h);    

var elem = svg.selectAll("g")
         .data(dataset) 

var elemEnter = elem.enter()
                .append("g")

var rects = elemEnter.selectAll("rect")
            .data(dataArr)
            .enter()
            .append("rect")
            .attr("x", function(d, i) {
                console.log(i);
                return 75;
            })
            .attr("y", function(d, i) {
                return (i * 50) + 25;
            });

For reference, this is what it looks like when I print out dataArr in the console. [Object, Object, Object]

Thanks so much for the help. I'm stuck trying to understand why it loops more than once through the data while trying to create rects. In addition, this is th eonly place in the code that has rects.

You might be seeing the cross product of the number of elements in dataset and the number of elements in dataAttr because the code above is binding dataset first:

var elem = svg.selectAll("g")
    .data(dataset) 

var elemEnter = elem.enter()
    .append("g") 

When working with d3.js, chrome 'inspect element' feature can be super useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM