D3-hierarchy implements several popular techniques for visualizing hierarchical data through layout algorithms that transform tree structures into visual coordinates. It provides node-link diagrams (tree, cluster), adjacency diagrams (partition), enclosure diagrams (treemap, pack), and comprehensive node traversal methods.
npm install d3-hierarchyimport {
hierarchy,
stratify,
cluster,
tree,
treemap,
partition,
pack
} from "d3-hierarchy";For CommonJS:
const {
hierarchy,
stratify,
cluster,
tree,
treemap,
partition,
pack
} = require("d3-hierarchy");import { hierarchy, tree } from "d3-hierarchy";
// Create hierarchy from nested data
const data = {
name: "root",
children: [
{ name: "child1" },
{ name: "child2", children: [{ name: "grandchild" }] }
]
};
const root = hierarchy(data);
// Apply tree layout
const treeLayout = tree().size([800, 400]);
const treeRoot = treeLayout(root);
// Access computed coordinates
console.log(treeRoot.x, treeRoot.y); // root position
treeRoot.descendants().forEach(node => {
console.log(node.data.name, node.x, node.y);
});D3-hierarchy is built around these key components:
Create hierarchical data structures from nested objects or flat tabular data. The foundation for all layout algorithms.
function hierarchy(data, children);
function stratify();Node-link tree diagrams using the Reingold-Tilford "tidy" algorithm and cluster/dendrogram layouts.
function tree();
function cluster();Recursive space-filling layouts that subdivide area into rectangles, with multiple tiling methods.
function treemap();
function treemapSquarify();
function treemapBinary();
function treemapDice();
function treemapSlice();
function treemapSliceDice();
function treemapResquarify();Partition layouts create adjacency diagrams, while circle packing creates enclosure diagrams with nested circles.
function partition();
function pack();
function packSiblings(circles);
function packEnclose(circles);Comprehensive traversal, manipulation, and computation methods available on all hierarchy nodes.
// Node traversal methods
node.each(callback);
node.eachBefore(callback);
node.eachAfter(callback);
node.descendants();
node.ancestors();
node.leaves();
// Node computation methods
node.sum(value);
node.sort(compare);
node.count();class Node {
constructor(data);
// Properties
data: any;
depth: number;
height: number;
parent: Node | null;
children?: Node[];
value?: number;
// Layout-specific coordinates (set by layout functions)
x?: number;
y?: number;
x0?: number; // treemap, partition
y0?: number; // treemap, partition
x1?: number; // treemap, partition
y1?: number; // treemap, partition
r?: number; // pack
}