Instantly share code, notes, and snippets.

@mbostock /.block
Last active Sep 30, 2017

Embed
What would you like to do?
Radial Force
license: gpl-3.0

This example shows how to create a custom “radial” force that places nodes in a circle with a configurable radius and center. The red nodes form a circle of approximate radius 100px, and the blue nodes approximately 200px.

<!DOCTYPE html>
<meta charset="utf-8">
<svg width="960" height="500" viewBox="-480 -250 960 500">
<circle r="100" stroke="brown" stroke-opacity="0.5" fill="none"></circle>
<circle r="200" stroke="steelblue" stroke-opacity="0.5" fill="none"></circle>
</svg>
<script src="https://d3js.org/d3-array.v1.min.js"></script>
<script src="https://d3js.org/d3-collection.v1.min.js"></script>
<script src="https://d3js.org/d3-dispatch.v1.min.js"></script>
<script src="https://d3js.org/d3-quadtree.v1.min.js"></script>
<script src="https://d3js.org/d3-selection.v1.min.js"></script>
<script src="https://d3js.org/d3-timer.v1.min.js"></script>
<script src="https://d3js.org/d3-force.v1.min.js"></script>
<script>
var nodes = [].concat(
d3.range(80).map(function() { return {type: "a"}; }),
d3.range(160).map(function() { return {type: "b"}; })
);
var node = d3.select("svg")
.append("g")
.selectAll("circle")
.data(nodes)
.enter().append("circle")
.attr("r", 2.5)
.attr("fill", function(d) { return d.type === "a" ? "brown" : "steelblue"; })
var simulation = d3.forceSimulation(nodes)
.force("charge", d3.forceCollide().radius(5))
.force("r", d3.forceRadial(function(d) { return d.type === "a" ? 100 : 200; }))
.on("tick", ticked);
function ticked() {
node
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment