Skip to content

Instantly share code, notes, and snippets.

@d3indepth
Last active June 3, 2020 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save d3indepth/ceb8d9e5ded610a9df1e0adb98efd748 to your computer and use it in GitHub Desktop.
Save d3indepth/ceb8d9e5ded610a9df1e0adb98efd748 to your computer and use it in GitHub Desktop.
Cluster layout
license: gpl-3.0
height: 240
border: no
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<title>Cluster layout</title>
</head>
<style>
.node {
fill: steelblue;
stroke: none;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 1px;
}
</style>
<body>
<svg width="400" height="220">
<g transform="translate(5, 5)">
<g class="links"></g>
<g class="nodes"></g>
</g>
</svg>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
<script>
var data = {
"name": "A1",
"children": [
{
"name": "B1",
"children": [
{
"name": "C1",
"value": 100
},
{
"name": "C2",
"value": 300
},
{
"name": "C3",
"value": 200
}
]
},
{
"name": "B2",
"value": 200
}
]
}
var clusterLayout = d3.cluster()
.size([400, 200])
var root = d3.hierarchy(data)
clusterLayout(root)
// Nodes
d3.select('svg g.nodes')
.selectAll('circle.node')
.data(root.descendants())
.enter()
.append('circle')
.classed('node', true)
.attr('cx', function(d) {return d.x;})
.attr('cy', function(d) {return d.y;})
.attr('r', 4);
// Links
d3.select('svg g.links')
.selectAll('line.link')
.data(root.links())
.enter()
.append('line')
.classed('link', true)
.attr('x1', function(d) {return d.source.x;})
.attr('y1', function(d) {return d.source.y;})
.attr('x2', function(d) {return d.target.x;})
.attr('y2', function(d) {return d.target.y;});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment