1

我计划为动态创建的数据集的节点创建树状结构,并希望为力有向图设置所有节点的 y 轴坐标。换句话说,我希望节点位于级别中(如树结构),而节点可以在 x 轴上自由移动和优化自身。

最终结果应该是一棵树,其中节点位于分配的级别,而不是默认情况下的径向。兄弟链接不应重叠,并且尽可能短(逻辑分组,因此希望通过力图做到这一点)。
如果有人有比这更简单的解决方案,那么我会全力以赴。

代码提取:

ldLinks = [
{source: "root", target: "1", source_level: 0, target_level: 1},
{source: "root", target: "2", source_level: 0, target_level: 1},
{source: "root", target: "3", source_level: 0, target_level: 1},
{source: "root", target: "4", source_level: 0, target_level: 1},
{source: "1", target: "1.1", source_level: 1, target_level: 2},
{source: "1", target: "1.2", source_level: 1, target_level: 2},
{source: "2", target: "2.1", source_level: 1, target_level: 3},
{source: "2", target: "2.2", source_level: 1, target_level: 3},
{source: "3", target: "3.1", source_level: 1, target_level: 3},
{source: "4", target: "3.2", source_level: 1, target_level: 3},
{source: "4", target: "3.3", source_level: 1, target_level: 3},
{source: "3", target: "3.2", source_level: 2, target_level: 3},
{source: "3", target: "4.1", source_level: 2, target_level: 3},
{source: "2.1", target: "5.1", source_level: 3, target_level: 4},
{source: "3.1", target: "5.1", source_level: 3, target_level: 4},
{source: "1", target: "5", source_level: 1, target_level: 4},
];

var dNodes = {};

// Compute the distinct dNodes from the ldLinks.
ldLinks.forEach(function(link) {
    link.source = dNodes[link.source] || (dNodes[link.source] = {name: link.source, level: link.source_level});
    link.target = dNodes[link.target] || (dNodes[link.target] = {name: link.target,  level: link.target_level});
});

//parameterize nodes
for (var sNodeName in dNodes) {
    //dNodes[sNodeName].fixed = (only fixed along y-axis)
    dNodes[sNodeName].y = (dNodes[sNodeName].level * 50)
}
4

1 回答 1

0

嘘!

感谢 Limin 对此答案的评论!

我设置force.gravity(0),然后在函数中添加边界( .attr("cx/cy")): nodetick()

function tick() {
    link
        .attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    node
        .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
        .attr("cx", function(d) { return d.x = Math.max(8, Math.min(width - 8, d.x)); })
        .attr("cy", function(d) { return d.y = Math.max(100*d.level, Math.min(100*d.level, d.y)); });
}
于 2014-11-20T16:12:28.200 回答