Code

D3.js

Treemap

Advanced Hierarchical treemap using d3.hierarchy() to build the tree, .sum() to roll up leaf values, and d3.treemap() for squarified tiling. d3-hierarchy/treemap

// Build hierarchy from nested data
const root = d3.hierarchy(data)
  .sum(d => d.value ?? 0)    // roll-up leaf values
  .sort((a, b) => b.value - a.value);

// Compute x0, y0, x1, y1 on each node
d3.treemap()
  .size([width, height])
  .paddingOuter(4)
  .paddingInner(2)
  .round(true)(root);

// Render leaves
const leaf = svg.selectAll('g')
  .data(root.leaves())
  .join('g')
  .attr('transform',
    d => `translate(${d.x0},${d.y0})`);

leaf.append('rect')
  .attr('width',  d => d.x1 - d.x0)
  .attr('height', d => d.y1 - d.y0)
  .attr('fill', d => color(d.parent.data.name));

leaf.append('text')
  .attr('x', 4).attr('y', 14)
  .text(d => d.data.name);
Key APIs
  • d3.hierarchy(data) — wraps nested data in a node hierarchy
  • .sum(accessor) — accumulates leaf values up the tree
  • d3.treemap().size([w,h]) — computes x0,y0,x1,y1 for each node
  • .paddingOuter(px) / .paddingInner(px) — spacing between groups and siblings
  • root.leaves() — returns only the leaf nodes (no children)
  • root.descendants() — returns all nodes (ancestors + leaves)