D3 tree vertical separation

前端 未结 4 523
时光说笑
时光说笑 2020-12-30 08:03

I am using the D3 tree layout, such as this one: http://mbostock.github.com/d3/talk/20111018/tree.html

I have modified it for my needs and am running into an issue.

4条回答
  •  旧时难觅i
    2020-12-30 09:04

    I was able to figure this out with help from a user on Google Groups. I was not able to find the post. The solution requires you to modify D3.js in one spot, which is not recommended but it was the only to get around this issue that I could find.

    Starting around line 5724 or this method: d3_layout_treeVisitAfter

    change:

    d3_layout_treeVisitAfter(root, function(node) {
        node.x = (node.x - x0) / (x1 - x0) * size[0];
        node.y = node.depth / y1 * size[1];
        delete node._tree;
    });
    

    to:

    d3_layout_treeVisitAfter(root, function(node) {
        // make sure size is null, we will make it null when we create the tree
        if(size === undefined || size == null) 
        { 
            node.x = (node.x - x0) * elementsize[0]; 
            node.y = node.depth * elementsize[1]; 
        } 
        else 
        { 
            node.x = (node.x - x0) / (x1 - x0) * size[0];
            node.y = node.depth / y1 * size[1]; 
        } 
        delete node._tree;
    });
    

    Below add a new variable called: elementsize and default it to [ 1, 1 ] to line 5731

    var hierarchy = d3.layout.hierarchy().sort(null).value(null)
        , separation = d3_layout_treeSeparation
        , elementsize = [ 1, 1 ] // Right here
        , size = [ 1, 1 ];
    

    Below that there is a method called tree.size = function(x). Add the following below that definition:

    tree.elementsize = function(x) {
        if (!arguments.length) return elementsize;
        elementsize = x;
        return tree;
    };
    

    Finally when you create the tree you can change the elementsize like so

    var tree = d3.layout.tree()
                 .size(null)
                 .elementsize(50, 240);
    

提交回复
热议问题