Force simulation - test
Grouped nodes + links
by navinleon
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.1.1/d3.min.js"></script>
<svg width="960" height="600"></svg>
CSS
.links line {
stroke: #999;
stroke-opacity: 0.6;
}
.nodes circle {
stroke: #fff;
stroke-width: 1.5px;
} 300px;
JavaScript
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var color = d3.scaleOrdinal(d3.schemeCategory20);
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function(d) { return d.id; }))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 4, height / 3));
var nodes = [
{"id": "Aug", "name": "Paul" },
{"id": "Aug", "name": "Ian" },
{"id": "Aug", "name": "Andy" },
{"id": "Sep", "name": "Gabby" },
{"id": "Sep", "name": "Vicky" },
{"id": "Oct", "name": "Dylan" },
{"id": "Oct", "name": "Finley" },
{"id": "Oct", "name": "Rudi" }
]
var links = [
{"source": "Aug", "target": "Aug" },
{"source": "Aug", "target": "Aug" },
{"source": "Aug", "target": "Aug" },
{"source": "Sep", "target": "Sep" },
{"source": "Sep", "target": "Sep" },
{"source": "Oct", "target": "Oct" },
{"source": "Oct", "target": "Oct" }
]
var link = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(links)
.enter()
.append("line")
.attr("stroke-width",2);
var node = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(nodes)
.enter()
.append("circle")
.attr("r", 6)
.attr("fill", function(d) { return color(d.id); })
var label = svg.selectAll(".mytext")
.data(nodes)
.enter()
.append("text")
.text(function (d) { return d.name; })
.style("text-anchor", "middle")
.style("fill", "#555")
.style("font-family", "Arial")
.style("font-size", 12);
simulation
.nodes(nodes)
.on("tick", ticked);
simulation.force("link")
.links(links);
function ticked() {
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...