Skip to content

Instantly share code, notes, and snippets.

@ojassvi
Last active June 26, 2018 17:37
Show Gist options
  • Save ojassvi/ffe8a50d24065184db144150f8facd04 to your computer and use it in GitHub Desktop.
Save ojassvi/ffe8a50d24065184db144150f8facd04 to your computer and use it in GitHub Desktop.
cluster 2
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
svg {
border: 1px solid red;
}
circle {
fill: none;
}
</style>
</head>
<body>
<script>
var width = 400,
height = 400,
padding = 1, // separation between same-color nodes
radius = 6;
var n = 100, // total number of nodes
m = 5; // number of distinct clusters
var nodes = [ { size: 10 }, { size: 20}, { size: 30 } ]
var force = d3.forceSimulation()
.nodes(nodes)
.force('charge', d3.forceManyBody().strength(-10))
.force('collide', d3.forceCollide().radius(d => d.size + 10).strength(5))
.force('x', d3.forceX(width / 2).strength(0.1))
.force('y', d3.forceY(height / 2).strength(0.1))
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
var node = svg.selectAll('.node')
.data(nodes)
var node_enter = node.enter().append('g')
.attr('class', 'node')
node_enter.append('circle')
.attr('r', function(d){ return d.size })
.attr('stroke', 'blue')
force.on('tick', function(){
svg.selectAll('.node')
.attr('transform', function(d){
return 'translate(' + d.x + ',' + d.y + ')' })
})
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment