D3 - Treemap Layout

> Data Visualization (vis|viz|graphic|image) > D3 (Data-Driven Documents) > D3 - Layout Module

1 - About

treemap in D3 is implemented as a layout.

v4.

You pass the root node of a tree to the treemap function and it will then add the coordinates of the tile to each node.

Advertising

3 - Steps

  • Create a tree
  • Call tree.sum or tree.count because treemap requires the value property for each node
  • Apply the treemap function on it

4 - Example

  • Create a tree with a CSV and the stratify method
var stratify = d3.stratify()
    .parentId(function (d) {
        return d.id.substring(0, d.id.lastIndexOf("\\"));
    });
 
var data = d3.csvParse(`id,value
root,0
root\\child1,10
root\\child2,20
root\\child3,15
root\\child4,30
`);
var tree = stratify(data);
  • Create and calculate the mandatory value property
tree.sum(function(d) { return d.value});
  • Definition of the treemap layout and apply it to the tree
var width = 600, height = 300;
var treemap = d3.treemap()
    .size([width, height])
    .round(true)
    .padding(1);
 
// Apply to the tree
treemap(tree);
console.log(tree)

Treemap will add the coordinates of each rectangle to each node:

  • x0
  • x1
  • y0
  • y1

You use this coordinates after to draw the treemap.

var color = d3.scaleOrdinal(d3.schemeCategory20);
 
var svg = d3.select("body")
  .append("svg")
  .attr("width",width)
  .attr("height",height);
 
var cell = svg.selectAll("g")
            .data(tree.leaves())
            .enter().append("g")
            .attr("transform", function (d) {
                return "translate(" + d.x0 + "," + d.y0 + ")";
            });
 
        cell.append("rect")
            .attr("id", function (d) {
                return d.data.id;
            })
            .attr("width", function (d) {
                return d.x1 - d.x0;
            })
            .attr("height", function (d) {
                return d.y1 - d.y0;
            })
            .attr("fill", function (d) {
                 var a = d.ancestors();
                 return color(a[a.length - 2].id);
            });
 
       cell.append("title")
        .text(function (d) {
            return d.id + "\n" + d.value;
        });

Advertising

5 - Example

5.1 - Csv + HTML Div

Squarified treemap of classes where each node is mapped to a rectangular HTML div element; although HTML is less expressive than SVG, it is supported on older browsers.

https://bl.ocks.org/mbostock/b4c0f143db88a9eb01a315a1063c1d77

5.2 - Svg + Count / Size

5.3 - Svg + URL

5.4 - Drill / Zoomable

viz/d3/layout/treemap.txt · Last modified: 2017/10/21 16:55 by gerardnico