Space out nodes evenly around root node in D3 force layout

流过昼夜 提交于 2019-12-02 23:59:49

Yes, force layout is a perfect tool for situations like yours.

You just need to change a little initialization of the layout, like this

force.nodes(nodes)
    .links(json.links)
    .charge(function(d){
        var charge = -500;
        if (d.index === 0) charge = 10 * charge;
        return charge;
    });

and voila

Explanation. I had to remove settings for friction and linkDistance since they affected placement in a bad way. The charge for root node is 10 times larger so that all other nodes are dominantly pushed away from the root. Other nodes also repel each other, and the perfect symmetry is achieved at the end, as a result.

Jsfiddle is here.


I see from your code that you attempted to affect distance from the root node and other nodes by utilizing linkDistance that is dependant on data. However, it might be better (although counter-intuitive) to use linkStrength for that purpose, like this

force.nodes(nodes)
    .links(json.links)
    .linkStrength(function (d) {
        return d.value / 100.0;
    })
    .charge(function(d){
        var charge = -500;
        if (d.index === 0) charge = 10 * charge;
        return charge;
    });

but you need to experiment.


For centering and fixing the root node, you can use this

nodes[0].fixed = true;
nodes[0].x = width / 2;
nodes[0].y = height / 2;

but before initialization of layout, like in this Jsfiddle.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!