我打算为动态创建的数据集创建一个树状结构,并且想要为力导向图设置所有节点的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)
}
答案 0 :(得分:0)
好哇!
感谢Limin从this answer发表的评论!
我设置了force.gravity(0)
,然后在.attr("cx/cy")
函数中向node
添加了边界(tick()
):
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)); });
}