D3.JS 显示同一层级的所有叶子
Display all the leafs on the same level with D3.JS
我最近开始使用 D3.js 来以径向树的形式可视化一棵树,如 Colapsible Radial Tree 中所示,但是我在修改代码时遇到了一些问题。
我使用 1 中的代码在同一个 'level' 上显示所有叶子。我的方法如下:
首先,使用以下代码计算树的最大深度,以了解将树的所有叶子放在哪里:
var maxDepth = getDepth(source);
function getDepth(obj) {
var depth = 0;
if (obj.children) {
obj.children.forEach(function (d) {
var tmpDepth = getDepth(d)
if (tmpDepth > depth) {
depth = tmpDepth
}
})
}
return 1 + depth}
然后,遍历树的所有节点,每当遇到没有children的节点(=叶子),位置设置为:
nodes.forEach(function(d) {
if (d.children)
{
d.y = d.depth * 60;
}else
d.y = maxDepth * 60;})
它似乎工作正常,除了一些节点的位置不正确并且有时重叠。
如何调整代码以更有效地传播节点?完整代码可用 here.
使用 d3 的 cluster 布局,它被设计为将树叶放在同一层
https://github.com/mbostock/d3/wiki/Cluster-Layout
https://bl.ocks.org/mbostock/4063570
var tree = d3.layout.cluster()
.size([360, diameter / 2 - 80])
.separation(function(a, b) { return (a.parent == b.parent ? 1 : 5) / a.depth; });
...
// Normalize for fixed-depth.
//nodes.forEach(function(d) { d.y = d.depth * 80; }); // get rid of this line (or amend it) as it resets the leaves to one level below the parent
我最近开始使用 D3.js 来以径向树的形式可视化一棵树,如 Colapsible Radial Tree 中所示,但是我在修改代码时遇到了一些问题。
我使用 1 中的代码在同一个 'level' 上显示所有叶子。我的方法如下:
首先,使用以下代码计算树的最大深度,以了解将树的所有叶子放在哪里:
var maxDepth = getDepth(source);
function getDepth(obj) {
var depth = 0;
if (obj.children) {
obj.children.forEach(function (d) {
var tmpDepth = getDepth(d)
if (tmpDepth > depth) {
depth = tmpDepth
}
})
}
return 1 + depth}
然后,遍历树的所有节点,每当遇到没有children的节点(=叶子),位置设置为:
nodes.forEach(function(d) {
if (d.children)
{
d.y = d.depth * 60;
}else
d.y = maxDepth * 60;})
它似乎工作正常,除了一些节点的位置不正确并且有时重叠。
如何调整代码以更有效地传播节点?完整代码可用 here.
使用 d3 的 cluster 布局,它被设计为将树叶放在同一层
https://github.com/mbostock/d3/wiki/Cluster-Layout
https://bl.ocks.org/mbostock/4063570
var tree = d3.layout.cluster()
.size([360, diameter / 2 - 80])
.separation(function(a, b) { return (a.parent == b.parent ? 1 : 5) / a.depth; });
...
// Normalize for fixed-depth.
//nodes.forEach(function(d) { d.y = d.depth * 80; }); // get rid of this line (or amend it) as it resets the leaves to one level below the parent