In D3 v4 with the force module, how do you update the parameters of the simulation once you have initialized the graph?
More precisely, I am trying to change the .forceLink
and .forceManyBody
of the force directed graph when the user clicks one of its nodes.
var node = svg
.append("g")
.attr("class", "gnodes")
.selectAll(".node")
.data(graph.nodes)
.enter()
.append("g")
.attr("class", "node")
.on('dblclick', connectedNodes); //calls for change in simulation parameters
So far I have been able to update it by duplicating the simulation under the connectedNodes function:
function connectedNodes() {
//new parameters
linkDistance = 5;
fCharge = -10;
//replicates the initial simulation code
simulation = d3.forceSimulation()
.force("link", d3.forceLink()
.id(function(d) {return d.id;})
.distance(linkDistance)
)
.force("collide", d3.forceCollide()
.radius(function(d){return d.r + 10})
.strength(1)
)
.force("charge", d3.forceManyBody()
.strength(fCharge)
)
.force("center", d3.forceCenter(width / 2, height / 2));
simulation.nodes(graph.nodes).on("tick", ticked);
simulation.force("link").links(graph.links);
Although this works it is very redundant. Is there a way in which the simulation can be refreshed with the new parameters? I have tried the following but it does not work
function connectedNodes() {
//new parameters
linkDistance = 5;
fCharge = -10;
//restart simulation with new parameters
simulation.restart();
}