javascript - 树形图,在 D3.js 中 x 和 y 属性来自哪里?

标签 javascript d3.js

这是 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);

当我记录节点和链接时,它说有 xy 属性:

enter image description here

我的 json 文件是这样的:

enter image description here

这两个属性从何而来?

最佳答案

这是因为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)

这就是数据中新的 xy 属性以及其他属性的来源(您可以在中查看 depth你的截图)。

PS:这是 D3 v3.x。在 D3 v4 中,d3.layout.cluster() 已更改,现在是 d3.cluster()

关于javascript - 树形图,在 D3.js 中 x 和 y 属性来自哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42046339/

相关文章:

d3.js - 复杂的 d3.nest() 操作

javascript - 根据输入值添加和删除下拉列表中的选项

javascript - 如何确定在 ember 中观察到的数组中添加/删除的项目?

javascript - Bootstrap Dropdown 永久显示 - 不特定于按钮点击

javascript - 使用 foreignObject 在 d3js 强制布局中制作 contenteditable 标签并在 Chrome 上拖动

javascript - SVG 文本在 IE 中消失,直到我点击它

javascript - 在 d3.js 中制作弧线

javascript - 为什么将函数定义包装在立即函数中?

来自 Date() 对象的 javascript 格式化时间

d3.js - D3匿名函数中的第三个变量