強制レイアウトを使用してグラフを表示しようとすると問題が発生します。頂点用とエッジ用の 2 つの csv ファイルを使用します。よくわかりませんが、d3.csv メソッドは非同期であり、そのうちの 2 つを使用しているため、「同時実行」の問題を回避するために一方を他方に挿入する必要があると思います (最初に d3.csv を呼び出そうとしました)。 csv を 2 回、個別に作成して、問題が発生しました)。
私のcsvの構造は次のとおりです。
エッジの場合:
source,target
2,3
2,5
2,6
3,4
ノードの場合:
index,name
1,feature1
2,feature2
3,feature3
私の最初の試みは:
// create the force layout
var force = d3.layout.force()
.charge(-120)
.linkDistance(30)
.size([width, height]);
var node, linked;
// we read the edges
d3.csv("csvEdges.csv", function(error, data) {
edg = data;
// we read the vertices
d3.csv("csvVertices.csv", function(error2, data2) {
ver = data2;
force.nodes(data2)
.links(data)
.start();
node = svg.selectAll(".node")
.data(data2)
.enter()
.append("circle")
.attr("class", "node")
.attr("r", 12)
.style("fill", function(d) {
return color(Math.round(Math.random()*18));
})
.call(force.drag);
linked = svg.selectAll(".link")
.data(data)
.enter()
.append("line")
.attr("class", "link");
force.on("tick", function() {
linked.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("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
しかし、私は得る:
"TypeError: Cannot call method 'push' of undefined."
何が問題なのかわかりません。リンクのプッシュに関係していると思います。おそらく問題は、d3 がリンクをノードのオブジェクトと照合する方法に関連していると読みました (この場合、私のノードには 2 つのフィールドがあります)。だから私は次のことを試しました(私はこれを他の質問hereで見ました):
// we read the edges
d3.csv("csvEdges.csv", function(error, data) {
edg = data;
// we read the vertices
d3.csv("csvVertices.csv", function(error2, data2) {
ver = data2;
force.nodes(data2)
.start();
//.links(data);
var findNode = function(id) {
for (var i in force.nodes()) {
if (force.nodes()[i]["index"] == id) return force.nodes()[i]
};
return null;
};
var pushLink = function (link) {
//console.log(link)
if(findNode(link.source)!= null && findNode(link.target)!= null) {
force.links().push ({
"source":findNode(link.source),
"target":findNode(link.target)
})
}
};
data.forEach(pushLink);
[...]
しかし、この場合、私はたくさんのものを手に入れます:
Error: Invalid value for <circle> attribute cy="NaN"
この場合、何が問題なのかわかりません。