Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active June 12, 2021 04:25
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mbostock/cd98bf52e9067e26945edd95e8cf6ef9 to your computer and use it in GitHub Desktop.
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