Draw a Treemap
Learn how to draw a treemap to show hierarchical data.
We'll cover the following...
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 size400 x 400and withpadding(2)to separate different countries from each other within the treemap. - Lines 59-60: We have
d3.hierarchywhich 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. - Lines 61-65: We have appended the
gtag for each leaf of the data, which arecountriesin our case. Then wetranslateeachgtag according to its position in the treemap. - Lines 66-69: We have appended a rectangle for each
countryin the data, and we have defined thewidthandheightof each rectangle on the basis of population. Then we have given color to eachcountryon the basis of the continent (parent of the child in the hierarchy) to which it belongs.Countriesin the same continent have the same color. - Lines 70-72: We have added
textto each rectangle using thetextmethod.