这是 JavaScript 代码:
d3.json("city.json", function (error, root) {
var nodes = cluster.nodes(root);
var links = cluster.links(nodes);
console.log(nodes);
console.log(links);
var link = gCluster.selectAll(".link")
.data(links)
.enter()
.append("path")
.attr("class", "link")
.attr("d", diagonal);
当我记录节点和链接时,它说有 x
和 y
属性:
我的 json 文件是这样的:
这两个属性从何而来?
最佳答案
这是因为d3.layout.cluster()
。
在你的代码中,在 d3.json
函数之前,你可能有这样的东西:
var cluster = d3.layout.cluster();
然后,当您这样做时:
var nodes = cluster.nodes(root);
var links = cluster.links(nodes);
您正在对您的数据调用 d3.layout.cluster()
。
d3.layout.cluster()
有什么作用?根据API :
These layouts follow the same basic structure: the input argument to the layout is the root node of the hierarchy, and the output return value is an array representing the computed positions of all nodes. Several attributes are populated on each node:
- parent - the parent node, or null for the root.
- children - the array of child nodes, or null for leaf nodes.
- depth - the depth of the node, starting at 0 for the root.
- x - the computed x-coordinate of the node position.
- y - the computed y-coordinate of the node position.
(emphasis mine)
这就是数据中新的 x
和 y
属性以及其他属性的来源(您可以在中查看 depth
你的截图)。
PS:这是 D3 v3.x。在 D3 v4 中,d3.layout.cluster()
已更改,现在是 d3.cluster()
。
关于javascript - 树形图,在 D3.js 中 x 和 y 属性来自哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42046339/