var graph = { nodes: d3.range(15).map(Object), links: [ {source: 0, target: 1, distance: 20 }, {source: 0, target: 2, distance: 40}, {source: 0, target: 3, distance: 80}, {source: 1, target: 4, distance: 20}, {source: 1, target: 5, distance: 40}, {source: 1, target: 6, distance: 80}, {source: 2, target: 7, distance: 12}, {source: 2, target: 8, distance: 8}, {source: 2, target: 9, distance: 6}, {source: 3, target: 10, distance: 10}, {source: 3, target: 11, distance: 10}, {source: 3, target: 12, distance: 2}, {source: 3, target: 13, distance: 2}, {source: 3, target: 14, distance: 2} ] }; var svg = d3.select("svg"), width = +svg.attr("width"), height = +svg.attr("height"); var color = d3.scaleOrdinal(d3.schemeCategory20); var simulation = d3.forceSimulation() .force("charge", d3.forceManyBody().strength(-30 )) .force("link", d3.forceLink().distance(function(d) { return d.distance } ).strength(2) ) .force("center", d3.forceCenter(width / 2, height / 2)) .force("collide",d3.forceCollide().strength(0).radius(0)) .alphaDecay(0.03) .velocityDecay(0.4); var link = svg.append("g") .attr("class", "links") .selectAll("line") .data(graph.links) .enter().append("line") .attr("stroke-width", 1); var node = svg.append("g") .attr("class", "nodes") .selectAll("circle") .data(graph.nodes) .enter().append("circle") .attr("r", 3) simulation .nodes(graph.nodes) .on("tick", ticked); simulation.force("link") .links(graph.links); function ticked() { var alpha = this.alpha(); var chargeStrength; if ( alpha > 0.2 ) { chargeStrength = (alpha - 0.2 / 0.8); } else { chargeStrength = 0; } this.force("charge", d3.forceManyBody().strength( -30 * chargeStrength )) link .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 dx; }) .attr("cy", function(d) { return dy; });
.links line { stroke: #999; stroke-opacity: 0.6; } .nodes circle { stroke: #fff; stroke-width: 1.5px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script> <svg width="500" height="300"></svg>