Javascript 将forcelayout从d3 v3转换为d3 v5
有人能帮我把书中提到的代码转换成D3V5吗?这是我的部分,但我得到的错误是svg.append(…).attr(…).selectAll(…).data(…).enter不是drawGraph的“函数”。实际上,我的目标是在强制布局结束后查找节点位置。使用这些位置,我将查找每个节点的距离Javascript 将forcelayout从d3 v3转换为d3 v5,javascript,d3.js,Javascript,D3.js,有人能帮我把书中提到的代码转换成D3V5吗?这是我的部分,但我得到的错误是svg.append(…).attr(…).selectAll(…).data(…).enter不是drawGraph的“函数”。实际上,我的目标是在强制布局结束后查找节点位置。使用这些位置,我将查找每个节点的距离 var graph = { "nodes": [{ "name": "a", "group": 1 }, { "name": "b",
var graph = {
"nodes": [{
"name": "a",
"group": 1
}, {
"name": "b",
"group": 8
}],
"links": [{
"source": 1,
"target": 0,
"value": 1
}
};
var width = 600;var height = 600;
function getPosition(force) {
return force.nodes().map(function(node) {
return {
name: node.name,
group: node.group,
x: node.x,
y: node.y
}
})
}
var color = d3.scaleOrdinal(d3.schemeCategory10);
var simulation = d3.forceSimulation(nodes)
.force("link", d3.forceLink().id(function(d,i) {
return i;
}).distance(30))
.force("charge", d3.forceManyBody().strength(-120 ))
.force("center", d3.forceCenter(width / 2,height / 2))
.on('end', function(){
var position = getPosition(simulation);
console.log(position)
});
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var drawGraph = function(graph) {
var link = svg.append('g')
.attr('class','links')
.selectAll("line")
.data(graph.link)
.enter()
.append("line");
var nodes = svg.append('g').attr("class", "nodes")
.selectAll("g")
.data(graph.nodes)
.enter()
.attr("r", 10)
.style("fill", function(d) {
return color(d.group);
})
.append("title")
.text(function(d) {
return d.name;
})
.call(simulation.drag);
simulation
.nodes(graph.nodes)
.on("tick", ticked);
simulation.force("link")
.links(graph.links);
function ticked(){
links.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; });
nodes.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
};
drawGraph(graph);
您的代码中有两个错误:第一个是
var simulation=d3.forceSimulation(nodes)
它应该是var simulation=d3.forceSimulation(graph.nodes)
,第二个是.data(graph.link)
它应该是.data(graph.links)
,这就是为什么您没有得到函数错误的原因“您的数据中没有它的链接谢谢您的回复。按照你的指示。我解决了错误,得到了节点位置。但代码不显示任何节点链接输出。你能帮我吗?再次谢谢你。我检查了密码。实际上我没有提到节点类型、大小和链接颜色。现在一切都好了。再次感谢你。