var data1 ={ "nodes": [{"id": "A"},{"id": "B"},{"id": "C"},{"id":"D"}], "links": [{"source": "A", "target": "B"}, {"source": "B", "target": "C"}, {"source": "C", "target": "A"}, {"source": "D", "target": "A"}] }
var data2 ={ "nodes": [{"id": "A"},{"id": "B"},{"id": "C"},{"id":"D"}], "links": [{"source": "A", "target": "B"}, {"source": "B", "target": "C"}, {"source": "C", "target": "A"}, {"source": "D", "target": "A"}] }
var height = 250; var width = 400;
var svg = d3.select("body").append("svg")
.attr("width",width)
.attr("height",height);
// FIRST SIMULATION
var simulation1 = d3.forceSimulation()
.force("link", d3.forceLink().id(function(d) { return d.id; }).distance(50))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 3, height / 2));
var link1 = svg.append("g")
.selectAll("line")
.data(data1.links)
.enter().append("line")
.attr("stroke","black");
var node1 = svg.append("g")
.selectAll("circle")
.data(data1.nodes)
.enter().append("circle")
.attr("r", 10)
.call(d3.drag()
.on("drag", dragged1)
.on("end", dragended1))
.attr("fill","crimson");
simulation1.nodes(data1.nodes)
.on("tick", ticked1)
.alphaDecay(0)
.force("link")
.links(data1.links);
function ticked1() {
link1
.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; });
node1
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
function dragged1(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended1(d) {
d.fx = null;
d.fy = null;
}
// SECOND SIMULATION
var simulation2 = d3.forceSimulation()
.force("link", d3.forceLink().id(function(d) { return d.id; }).distance(50))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width * 2 / 3, height / 2));
var link2 = svg.append("g")
.selectAll("line")
.data(data2.links)
.enter().append("line")
.attr("stroke","black");
var node2 = svg.append("g")
.selectAll("circle")
.data(data2.nodes)
.enter().append("circle")
.attr("r", 10)
.call(d3.drag()
.on("drag", dragged2))
.attr("fill","steelblue");
simulation2.nodes(data2.nodes)
.on("tick", ticked2)
.alphaDecay(0)
.force("link")
.links(data2.links);
function ticked2() {
link2
.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; });
node2
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
function dragged2(d) {
d.x = d3.event.x;
d.y = d3.event.y;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>