Ouroborus
Ouroborus

Reputation: 16865

"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:

before

and have it come out similar to:

after

Upvotes: 2

Views: 366

Answers (1)

helderdarocha
helderdarocha

Reputation: 23637

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 d.x instead.

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

Upvotes: 3

Related Questions