D3 - Treemap Layout

Card Puncher Data Processing


treemap in D3 is implemented as a layout.


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.


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


  • 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
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])

// Apply to the 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")

var cell = svg.selectAll("g")
            .attr("transform", function (d) {
                return "translate(" + d.x0 + "," + d.y0 + ")";

            .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);
        .text(function (d) {
            return d.id + "\n" + d.value;


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.


Svg + Count / Size

See https://bl.ocks.org/mbostock/4063582

Svg + URL


Drill / Zoomable

Level Treemap + Drill down

Global Treemap + Zoom In

Discover More
Card Puncher Data Processing
D3 - Hierarchy

tree operation in D3 are done in the hierarchy module. A tree will be passed to a hierarchical layout such as node.sumnode.countnode.value Nest d3.hierarchy....
Card Puncher Data Processing
D3 - Layout Module

Layouts module supply reusable, flexible visualization techniques by generating abstract data structures. The partition layout computes a two-dimensional spatial subdivision of a hierarchical (tree...
Card Puncher Data Processing
D3 - Tree

Data manipulation: layout: Tree - Example: tree
Tree Map Padding
Tree - Treemap Chart

Ben Shneiderman introduced tree maps in the early 90s as a visualization metaphor for displaying hierarchical trees. A tree map arranges hierarchical...

Share this page:
Follow us:
Task Runner