[英]“Leaf-justify” D3 tree graphs?
One way to do it is to discover the depth of the tree and set the depth
property of each node that doesn't have any children to that value. 一种实现方法是发现树的深度,并将没有任何子节点的每个节点的
depth
属性设置为该值。
Assuming your tree data is as follows: 假设您的树数据如下:
var data = [
{
"name": "Top Level",
"parent": "null",
"children": [
{
"name": "Level 2: A",
"parent": "Top Level",
"children": [ ...
And you created a tree using: 您使用以下方法创建了一棵树:
var tree = d3.layout.tree();
You can get the depth
of the tree by searching each node for the max value of depth
: 你可以得到
depth
通过搜索的最大值每个节点树的depth
:
var treeDepth = d3.max(tree(data[0]), function(d) { return d.depth; });
Once you have that, you can reset it every time you recompute the tree layout: 一旦有了它,就可以在每次重新计算树布局时将其重置:
tree.nodes(data[0]).forEach(function(d) {
var depthSize = 50;
if (!d.children) { // this node has no children
d.depth = treeDepth; // set depth to depth of tree
}
d.y = d.depth * depthSize; // recalculate y
});
This works for trees laid out as in your example (from left to right). 这适用于示例中从左到右排列的树木。 For top-down layouts you have to change
dx
instead. 对于自上而下的布局,您必须改为
dx
。
Here is a JSFiddle with a working solution adapted from this example . 这是一个JSFiddle,其中有一个适用于此示例的可行解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.