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/96649ce5ef72d53386790908fe785a6a to your computer and use it in GitHub Desktop.
Save d3indepth/96649ce5ef72d53386790908fe785a6a to your computer and use it in GitHub Desktop.
Treemap layout (with labels)
license: gpl-3.0
height: 240
border: no
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<title>Treemap layout (with labels)</title>
</head>
<style>
rect {
fill: cadetblue;
opacity: 0.3;
stroke: white;
}
text {
font-family: "Helvetica Neue", Helvetica, sans-serif;
fill: white;
font-size: 10px;
}
</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(16);
var rootNode = d3.hierarchy(data)
rootNode.sum(function(d) {
return d.value;
});
treemapLayout(rootNode);
var nodes = d3.select('svg g')
.selectAll('g')
.data(rootNode.descendants())
.enter()
.append('g')
.attr('transform', function(d) {return 'translate(' + [d.x0, d.y0] + ')'})
nodes
.append('rect')
.attr('width', function(d) { return d.x1 - d.x0; })
.attr('height', function(d) { return d.y1 - d.y0; })
nodes
.append('text')
.attr('dx', 4)
.attr('dy', 14)
.text(function(d) {
return d.data.name;
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment