[英]Processing a multidimensional data array with 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操作。 我想画几个圆圈而不合并:)
谢谢!
看到您提到您是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;
});
你可以看到这一切放在一起在这个捣鼓了一些细微的变化。
如果您想了解d3,我真的建议您阅读d3上的Scott Murray书,这是一个很好的介绍
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.