Skip to content

Instantly share code, notes, and snippets.



Forked from mbostock/.block
Last active Aug 29, 2015
What would you like to do?
Multi-Foci Force Layout

Click to perturb or drag the nodes!

This example demonstrates the flexibility of D3's force layout. By using position Verlet integration, it is easy to add custom forces to a layout. In this example, the nodes are clustered around four foci using additional forces: the odd nodes are pushed down, the even nodes are pushed up, and a similar bisecting force is applied laterally. These custom forces are based purely on the index of the node, but they could just as easily be derived from properties of data!

<!DOCTYPE html>
<meta charset="utf-8">
.node {
stroke-width: 1.5px;
<script src=""></script>
var width = 960,
height = 500;
var fill = d3.scale.category10();
var nodes = d3.range(100).map(function(i) {
return {index: i};
var force = d3.layout.force()
.size([width, height])
.on("tick", tick)
var svg ="body").append("svg")
.attr("width", width)
.attr("height", height);
var node = svg.selectAll(".node")
.attr("class", "node")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", 8)
.style("fill", function(d, i) { return fill(i & 3); })
.style("stroke", function(d, i) { return d3.rgb(fill(i & 3)).darker(2); })
.on("mousedown", function() { d3.event.stopPropagation(); });"opacity", 1e-6)
.style("opacity", 1);"body")
.on("mousedown", mousedown);
function tick(e) {
// Push different nodes in different directions for clustering.
var k = 6 * e.alpha;
nodes.forEach(function(o, i) {
o.y += i & 1 ? k : -k;
o.x += i & 2 ? k : -k;
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
function mousedown() {
nodes.forEach(function(o, i) {
o.x += (Math.random() - .5) * 40;
o.y += (Math.random() - .5) * 40;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment