Most basic treemap in d3.js

This post describes how to build a very basic treemap with d3.js. It takes into account a hierarchy dataset, stored at .csv format. See many other examples in the treemap section of the gallery. Learn more about the theory of treemaps in

Treemap section


  • The Html part of the code just creates a div that will be modified by d3 later on.

  • The first part of the javascript code set a svg area. It specify the chart size and its margin. Read more.

  • The input dataset used here is stored at the .csv format. The d3.stratify() function is thus needed for reformatting. read more.

  • Then, the d3.treemap() function can be used to compute the rectangle coordinates of each entity of the hierarchy.

  • Finally, it is possible to use these coordinates to add rectangles and labels with rect and text.
<!DOCTYPE html>
<meta charset="utf-8">

<!-- Load d3.js -->
<script src=""></script>

<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>


// set the dimensions and margins of the graph
var margin = {top: 10, right: 10, bottom: 10, left: 10},
  width = 445 - margin.left - margin.right,
  height = 445 - - margin.bottom;

// append the svg object to the body of the page
var svg ="#my_dataviz")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + + margin.bottom)
        "translate(" + margin.left + "," + + ")");

// Read data
d3.csv('', function(data) {

  // stratify the data: reformatting for d3.js
  var root = d3.stratify()
    .id(function(d) { return; })   // Name of the entity (column name is name in csv)
    .parentId(function(d) { return d.parent; })   // Name of the parent (column name is parent in csv)
  root.sum(function(d) { return +d.value })   // Compute the numeric value for each entity

  // Then d3.treemap computes the position of each element of the hierarchy
  // The coordinates are added to the root object above
    .size([width, height])

  // use this information to add rectangles:
      .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; })
      .style("stroke", "black")
      .style("fill", "#69b3a2");

  // and to add the text labels
      .attr("x", function(d){ return d.x0+10})    // +10 to adjust position (more right)
      .attr("y", function(d){ return d.y0+20})    // +20 to adjust position (lower)
      .text(function(d){ return})
      .attr("font-size", "15px")
      .attr("fill", "white")

Related blocks →