Skip to content

Instantly share code, notes, and snippets.

@d3indepth
Last active August 2, 2017 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d3indepth/e9e845cb419049497369af4347e4348a to your computer and use it in GitHub Desktop.
Save d3indepth/e9e845cb419049497369af4347e4348a to your computer and use it in GitHub Desktop.
Pack layout (with labels)
license: gpl-3.0
height: 330
border: no
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<title>Pack layout (with labels)</title>
</head>
<style>
circle {
fill: indianred;
opacity: 0.3;
stroke: white;
}
text {
font-family: "Helvetica Neue", Helvetica, sans-serif;
fill: white;
font-size: 10px;
text-anchor: middle;
}
</style>
<body>
<svg width="320" height="320">
<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 packLayout = d3.pack()
.size([300, 300]);
var rootNode = d3.hierarchy(data)
rootNode.sum(function(d) {
return d.value;
});
packLayout(rootNode);
var nodes = d3.select('svg g')
.selectAll('g')
.data(rootNode.descendants())
.enter()
.append('g')
.attr('transform', function(d) {return 'translate(' + [d.x, d.y] + ')'})
nodes
.append('circle')
.attr('r', function(d) { return d.r; })
nodes
.append('text')
.attr('dy', 4)
.text(function(d) {
return d.children === undefined ? d.data.name : '';
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment