简体   繁体   English

在d3中绑定数据会追加太多次

[英]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. 我有3个JSON对象的数组,我想在d3中绑定以创建一些矩形。 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. 作为参考,这是我在控制台中打印出dataArr时的样子。 [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. 我一直试图了解为什么它在尝试创建rect时会多次遍历数据。 In addition, this is th eonly place in the code that has rects. 此外,这是具有rect的代码中的唯一位置。

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: 您可能会看到数据集中元素数量与dataAttr中元素数量的乘积,因为上面的代码首先绑定了数据集:

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. 当使用d3.js时,chrome“检查元素”功能可能超级有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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