Skip to content

Instantly share code, notes, and snippets.

@d3indepth
Last active August 2, 2017 10:17
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/d4f8938a1fd0914b41ea7cb4e2480ca8 to your computer and use it in GitHub Desktop.
Save d3indepth/d4f8938a1fd0914b41ea7cb4e2480ca8 to your computer and use it in GitHub Desktop.
Treemap layout
license: gpl-3.0
height: 240
border: no
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<title>Treemap layout</title>
</head>
<style>
rect {
fill: cadetblue;
opacity: 0.3;
stroke: white;
}
</style>
<body>
<svg width="420" height="220">
<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 treemapLayout = d3.treemap()
.size([400, 200])
.paddingOuter(10);
var root = d3.hierarchy(data)
root.sum(function(d) {
return d.value;
});
treemapLayout(root);
d3.select('svg g')
.selectAll('rect')
.data(root.descendants())
.enter()
.append('rect')
.attr('x', function(d) { return d.x0; })
.attr('y', function(d) { return d.y0; })
.attr('width', function(d) { return d.x1 - d.x0; })
.attr('height', function(d) { return d.y1 - d.y0; })
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment