Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 44 ยท Layouts and Hierarchies

Hierarchies and Tree Layouts

Turn nested or flat data into a d3.hierarchy, walk it with descendants and links, and draw it as a tree or cluster diagram with d3.tree and d3.cluster.

Many data sets are trees: file systems, org charts, category menus, family trees. D3 treats them in two steps. First d3.hierarchy() wraps your data in a tree of nodes that know their parent, children, depth and height. Then a layout such as d3.tree() adds x and y coordinates to every node. You draw those coordinates yourself with SVG, so you keep full control of the look.

Layouts never draw anything. They only compute numbers and attach them to the nodes. That is why the same hierarchy can be shown as a tree, a treemap, a sunburst or a pack layout just by changing the layout function.

Creating a hierarchy

d3.hierarchy(root, children) takes a nested object. By default it reads the children array of each object.

JavaScript
const data = {
  name: "Company",
  children: [
    { name: "Engineering", children: [{ name: "Web" }, { name: "Mobile" }] },
    { name: "Sales" }
  ]
};
const root = d3.hierarchy(data);

Each node in the result has these fields:

Field Meaning
node.data your original object for that node
node.depth distance from the root (root is 0)
node.height distance to the deepest leaf below (a leaf is 0)
node.parent the parent node, null for the root
node.children array of child nodes, undefined for leaves
node.value set by .sum() (see below)

If your children live under another name, pass an accessor: d3.hierarchy(data, d => d.items).

Walking the tree

Nodes have helper methods that return plain arrays, so you can feed them straight into a data join:

  • root.descendants() returns the node and all nodes below it, in breadth-first order.
  • root.leaves() returns only the nodes without children.
  • root.links() returns {source, target} pairs, one per parent-child edge.
  • node.ancestors() goes from the node up to the root.
  • node.path(other) gives the shortest path between two nodes.
  • root.each(fn), root.eachBefore(fn) and root.eachAfter(fn) visit every node in different orders.
Inspect a hierarchy

Values, sorting and counting

Layouts such as treemap need a number on every node. Call root.sum(d => d.size): it adds the value of a node to the values of all its descendants and stores the total in node.value. root.count() instead counts leaves, which is handy for trees without sizes. To order siblings, use root.sort((a, b) => b.value - a.value).

Flat tables with stratify

Data often arrives as a flat table with an id and a parent id, for example from a CSV file. d3.stratify() turns it into the same kind of hierarchy:

JavaScript
const rows = [
  { id: "A", parent: "" },
  { id: "B", parent: "A" },
  { id: "C", parent: "A" },
  { id: "D", parent: "B" }
];
const root = d3.stratify()
  .id(d => d.id)
  .parentId(d => d.parent || null)(rows);

Exactly one row must have no parent. D3 throws a clear error for missing parents, duplicate ids and cycles, which makes broken data easy to find.

The tree layout

d3.tree() places nodes so that parents sit above the centre of their children and no nodes overlap (the Reingold-Tilford algorithm, improved by Buchheim et al.). You choose the size with .size([width, height]) or fix the spacing with .nodeSize([dx, dy]). Call the layout on a hierarchy and it fills in x and y:

A top-down tree diagram

The link generators d3.linkVertical() and d3.linkHorizontal() draw smooth curves between two points. For a left-to-right tree, swap the roles of the coordinates: use d.y for horizontal position and d.x for vertical, and pass .x(d => d.y).y(d => d.x) to linkHorizontal().

flowchart LR
  A["Nested or flat data"] --> B["d3.hierarchy or d3.stratify"]
  B --> C["Layout: d3.tree, cluster, treemap..."]
  C --> D["Nodes with x, y (and more)"]
  D --> E["Your SVG via a data join"]

A layout sits between the data and the drawing code.

Cluster layout

d3.cluster() is the sibling of d3.tree(). It puts all leaves at the same depth, which suits dendrograms and taxonomy diagrams where the leaves are the actual items. Use it exactly like the tree layout:

JavaScript
d3.cluster().size([width, height])(root);

Compare the two: in a tree, a leaf sits right below its parent level; in a cluster, every leaf is pushed to the bottom edge.

Radial trees

For a circular tree, set .size([2 * Math.PI, radius]) so x becomes an angle in radians and y a radius. Convert each node with d3.pointRadial(x, y), which returns [px, py], or use d3.linkRadial() for the edges. Radial layouts use space well for wide, shallow trees.

Common mistakes

  • Calling the layout on the raw data instead of on the hierarchy: d3.tree()(data) fails, you need d3.tree()(d3.hierarchy(data)).
  • Forgetting that x and y are only coordinates in the layout's own space: you still need to translate and scale them into the SVG.
  • Joining only leaves or only descendants when you wanted both nodes and links. Use root.links() for the edges and root.descendants() for the nodes.
  • Mutating children after calling the layout. Rebuild the hierarchy and re-run the layout instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does node.height mean in a d3 hierarchy?

    depth counts steps from the root; height counts steps down to the deepest leaf below. A leaf has height 0.
  2. 2. Which function turns a flat table of id and parentId rows into a hierarchy?

    d3.stratify reads the id and parent id of each row and builds the same node structure as d3.hierarchy.
  3. 3. What does d3.tree() do when you call it on a hierarchy?

    Layouts only compute coordinates. You draw the nodes and links yourself.
  4. 4. How does d3.cluster() differ from d3.tree()?

    A cluster layout aligns the leaves at the outer edge, which is typical for dendrograms.

Summary

  • d3.hierarchy wraps nested data in nodes with data, depth, height, parent and children.
  • descendants(), leaves() and links() return arrays that plug into data joins.
  • d3.stratify builds a hierarchy from flat id/parent rows.
  • d3.tree and d3.cluster add x and y; linkVertical, linkHorizontal and linkRadial draw the edges.

Next: Treemap, Partition and Pack Layouts