似乎如果在D3力布局中两个节点之间存在多个链接,D3就会选择一个并忽略其他节点。是否可以可视化多图?
答案 0 :(得分:7)
因此,事实证明d3 确实在节点之间呈现多个链接,只是它将它们相互重叠。我解决这个问题的方法是将链接绘制为路径(而不是行),并为每个路径添加不同的曲线。这意味着每个链接对象都需要一些东西来区分它与相同源节点和目标节点的其他对象。我的链接看起来像这样:
links: [
{"source": 0,"target": 1,"count": 1},
{"source": 1,"target": 2,"count": 1},
{"source": 1,"target": 3,"count": 1},
{"source": 1,"target": 4,"count": 1},
// same source and target with greater count
{"source": 1,"target": 4,"count": 2},
{"source": 1,"target": 4,"count": 3},
{"source": 1,"target": 4,"count": 4}
]
然后路径渲染代码看起来像
function tick() {
link.attr("d", function(d) {
var x1 = d.source.x,
y1 = d.source.y,
x2 = d.target.x,
y2 = d.target.y,
dx = x2 - x1,
dy = y2 - y1,
// Set dr to 0 for straight edges.
// Set dr to Math.sqrt(dx * dx + dy * dy) for a simple curve.
// Assuming a simple curve, decrease dr to space curves.
// There's probably a better decay function that spaces things nice and evenly.
dr = Math.sqrt(dx * dx + dy * dy) - Math.sqrt(300*(d.count-1));
return "M" + x1 + "," + y1 + "A" + dr + "," + dr + " 0 0,1 " + x2 + "," + y2;
});
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
}
这是展示方法的jsfiddle。
答案 1 :(得分:3)
您可以通过创建一组链接将多图表简单地编码为图形,其中每个链接都是表单的一个包:
{"links": [/* one or more links*/], "source": …, "target": …}
然后,您可以按常规运行强制定向布局以定位节点。然后,您需要适当地代表每个捆绑包,例如通过绘制平行线。
相关:Mike Bostock使用简单的黑客代表two parallel links between nodes,虽然这不容易扩展到更多的链接。