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:
- Line 55-57: We have defined a layout for our treemap using
d3.map()
with size400 x 400
and withpadding(2)
to separate different countries from each other within the treemap. - Line 58-59: 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 thepopulation
. - Line 60-64: We have appended the
g
tag for each leaf of the data, which arecountries
in our case. Then wetranslate
eachg
tag according to its position in the treemap. - Line 65-68: We have appended a rectangle for each
country
in the data, and we have defined thewidth
andheight
of each rectangle on the basis of population. Then we have given color to eachcountry
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. - Line 69-71: We have added
text
to each rectangle using thetext
method.