我最近开始使用 D3.js 来以径向树的形式可视化一棵树,如 Colapsible Radial Tree 中所示。 ,但是我在修改代码的时候遇到了一些问题。
我使用了1中的代码将所有叶子显示在同一“级别”上。我的方法如下:
首先,使用以下代码计算树的最大深度,以了解将树的所有叶子放在哪里:
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}
然后,循环遍历树的所有节点,每当遇到没有子节点的节点(=叶子)时,位置将设置为:
nodes.forEach(function(d) {
if (d.children)
{
d.y = d.depth * 60;
}else
d.y = maxDepth * 60;})
如何调整代码以更有效的方式传播节点?完整代码可查看here .
最佳答案
使用 d3 的簇布局,它旨在将叶子放置在同一级别
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
关于javascript - 使用D3.JS在同一层显示所有叶子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36773793/