简体   繁体   中英

“Leaf-justify” D3 tree graphs?

What do I need to do to get tree graphs to render such that nodes are justified towards the leaf side of the graph?

I'd like to take an arbitrary tree graph that might normally look like:

之前

and have it come out similar to:

后

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.

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 :

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.

Here is a JSFiddle with a working solution adapted from this example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM