使用d3.js处理多维数据数组

时间:2014-05-05 04:35:48

标签: javascript arrays multidimensional-array d3.js

目前我正在学习一些“D3.js”并试图了解数据处理和选择的方式。

我坚持自己为自己创建的以下任务。

理想情况下,我想要一些在功能上等同于:

的东西
    <svg>
        <circle r=​"20.5" cx=​"100" cy=​"200">​</circle>​
        <circle r=​"20.5" cx=​"300" cy=​"10">​</circle>​
    </svg>

我目前(我的逻辑)是:

    var matrix = [ [{ "x": 100, "y": 200 }], [{ "x": 300, "y": 10 }]];

    var result = d3.select("body").append("svg")  // Append SVG to end of Body
       .data(matrix) // select this data
       .selectAll("g") //g is a svg grouping tag
       .data(function (d) { return d; }) //Unwrap the first part of the array
       .enter() // Grab all the data that is new to the selection in each array
       .selectAll("g") 
       .data(function (d) { return d;}) // foreach each item inside the 1D array
       .enter() // For all the data that doesn't exist already in the SVG
       .append("circle") // Append Circle to the DOM with the following attributes
       .attr("r", 20.5)
       .attr("cx", function (d) { return d.x; })
       .attr("cy", function (d) { return d.y; });
    };

奇怪的是:

 var result = d3.select("body").append("svg")
        .data(matrix)
        .selectAll("g")         
        .enter()            
        .append("circle")
        .attr("r", 20.5)
        .attr("cx", function (d) { return d.x; })
        .attr("cy", function (d) { return d.y; });
    };

似乎能以某种方式获得数组中的第一项但不能正确迭代。我不太确定它是如何进入阵列的。

D3似乎距离我习惯的编程范例还有很大的一步,而且调试起来比较困难,所以如果有人能解释我哪里出错了会很棒。

哦,虽然这个例子很无用,但我可以使用merge命令将其展平 - 以便完全理解D3操作。我想在没有合并的情况下绘制几个圆圈:)

谢谢!

1 个答案:

答案 0 :(得分:0)

看到你提到你是d3的新手我会对基础知识做一些评论。

首先,我们试图在DOM上放置一些svg元素,所以首先我们必须有一个svg画布来处理。通常它在代码的早期设置,看起来像这样:

var svg = d3.select("body")
             .append("svg")
             .attr("width", 350)
             .attr("height", 250);

请注意,最好定义高度和宽度的变量(但我很懒)。

所以现在你有了画布让我们看看d3是如何迭代的。 d3遍历一个数组,因此你不必在一个数组中有一个数组,如下所示:

 var matrix = [ { "x": 100, "y": 200 }], [{ "x": 300, "y": 10 }];

现在你的第二块代码几乎就在那里,只需要重新安排一下。我们需要做的第一件事是使用svg.selectAll("circle")为svg画布中的圆创建占位符。接下来,我们使用data(matrix)将数据引入空占位符,并使用'enter()`进行绑定。现在我们所要做的就是附加圆圈并给它们一些属性,这是代码的其余部分

svg.selectAll("circle")
     .data(matrix)
     .enter()
     .append("circle")
     .attr("r", 20.5)
     .attr("cx", function (d) {
         return d.x;
     })
     .attr("cy", function (d) {
         return d.y;
     });

您可以在此fiddle中看到所有这些内容,并进行一些细微更改。

如果你想了解d3我真的建议在第3节获得Scott Murray的书,这是一个很好的介绍