关于这棵树,我其实有几个问题,但我会分开问。
我有一棵树(民主化),很明显,除了我附加在子节点上的一个小工具提示外,大部分都是一棵普通的d3水平树。
问题是,我怎样才能让树从容器的左上方展开,而不是从y轴的中间向外辐射?换句话说,我希望最终的结果是这样的。
START-----Parent 1-----Child 1
\
`---Child 2
等,其中START在SVG容器的左上角。注意:子节点应该因此向下和向右扩展。
我一直在研究x和y在这里是如何工作的,但我似乎不知道如何改变这个问题。
你可以通过修改x值来达到这个效果,在
nodes.forEach(function(d) { d.x = /*yourValues*/; d.y = d.depth * 180; });
你可能已经意识到了这一点,对于你的特殊问题,真正的关键将是为每个节点提供一个与它的级别(即兄弟姐妹)的节点数量相关的值。由于你提供的例子已经给出了一个 depth
的值,你可以通过节点迭代并统计这些值,最终得到一个数组,如。
node0 has 0 nodes before it in the same depth (depth 0)
node1 has 0 nodes before it in the same depth (depth 1)
node2 has 1 nodes before it in the same depth (depth 1)
UPDATE 你可以通过替换上述内容,找到兄弟姐妹的值,并达到理想的效果。forEach
的代码,并添加以下内容。
nodes.forEach(function(d) { //iterate through the nodes
if(d.parent != null){ //if the node has a parent
for(var i = 0; i < d.parent.children.length; i++){ //check parent children
if(d.parent.children[i].name == d.name){ //find current node
d.downset = i; //index is how far node must be moved down
}
}
d.parentDownset = d.parent.downset; //must also account for parent downset
}
if(d.downset == null){ d.downset = 0; }
if(d.parentDownset == null){ d.parentDownset = 0; }
d.x = (d.downset * 40) + (d.parentDownset * 40) + 20;
d.y = d.depth * 180;
});
另外,根据你的例子中孩子们的命名方式, 你可以直接解析出后面的数字。.
拿着 1
不在 Child 1.1
否则返回 0
对于 Child 1
和 Child 2
nodes.forEach(function(d,i) {
d.x = d.numberAfterPeriod * 40 + 20;
d.y = d.depth * 180;
});
我使用Angualr和D3js创建了这个,树根从左上方开始缩进。
请在这里找到github的链接。https:/github.comAnandanSelvaganesanangular-d3-tree。