Skip to content

Instantly share code, notes, and snippets.

@d3indepth
Last active May 1, 2020 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save d3indepth/181b398d5305cefcd10186617cb9250c to your computer and use it in GitHub Desktop.
Save d3indepth/181b398d5305cefcd10186617cb9250c to your computer and use it in GitHub Desktop.
Minimal force layout example
license: gpl-3.0
height: 320
border: no
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<title>Force layout</title>
</head>
<style>
circle {
fill: cadetblue;
}
</style>
<body>
<div id="content">
<svg width="300" height="300">
</svg>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
<script>
var width = 300, height = 300
var nodes = [{}, {}, {}, {}, {}]
var simulation = d3.forceSimulation(nodes)
.force('charge', d3.forceManyBody().strength(-20))
.force('center', d3.forceCenter(width / 2, height / 2))
.on('tick', ticked);
function ticked() {
var u = d3.select('svg')
.selectAll('circle')
.data(nodes)
u.enter()
.append('circle')
.attr('r', 5)
.merge(u)
.attr('cx', function(d) {
return d.x
})
.attr('cy', function(d) {
return d.y
})
u.exit().remove()
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment