Draw a Treemap

Learn how to draw a treemap to show hierarchical data.

We'll cover the following...

Treemap layout

As we have discussed in the previous lesson, we need the d3.treemap() API to define a layout for treemap. Additionally, we need some information in the data to know the location of each rectangle within the treemap. Don’t worry. D3.js provides another API d3.hierarchy(), which will add hierarchical information with data and will help us to draw the treemap.

Example

Let’s draw a treemap by taking dummy data of different countries situated on different continents. We will use the above-discussed APIs to draw a treemap in the following code.

Explanation

As shown in the above code:

  • Lines 56-58: We have defined a layout for our treemap using d3.map() with size 400 x 400 and with padding(2) to separate different countries from each other within the treemap.
  • Lines 59-60: We have d3.hierarchy which will add the positional information rectangles within the treemap. The .sum() function will help to determine the size of each rectangle on the basis of the population.
  • Lines 61-65: We have appended the g tag for each leaf of the data, which are countries in our case. Then we translate each g tag according to its position in the treemap.
  • Lines 66-69: We have appended a rectangle for each country in the data, and we have defined the width and height of each rectangle on the basis of population. Then we have given color to each country on the basis of the continent (parent of the child in the hierarchy) to which it belongs. Countries in the same continent have the same color.
  • Lines 70-72: We have added text to each rectangle using the text method.