MCPcopy Index your code
hub / github.com/d3/d3-hierarchy

github.com/d3/d3-hierarchy @v3.1.2

Chat with this repo
repository ↗ · DeepWiki ↗ · release v3.1.2 ↗ · + Follow
117 symbols 295 edges 58 files 0 documented · 0% 26 cross-repo links
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

d3-hierarchy

Many datasets are intrinsically hierarchical. Consider geographic entities, such as census blocks, census tracts, counties and states; the command structure of businesses and governments; file systems and software packages. And even non-hierarchical data may be arranged empirically into a hierarchy, as with k-means clustering or phylogenetic trees.

This module implements several popular techniques for visualizing hierarchical data:

Node-link diagrams show topology using discrete marks for nodes and links, such as a circle for each node and a line connecting each parent and child. The “tidy” tree is delightfully compact, while the dendrogram places leaves at the same level. (These have both polar and Cartesian forms.) Indented trees are useful for interactive browsing.

Adjacency diagrams show topology through the relative placement of nodes. They may also encode a quantitative dimension in the area of each node, for example to show revenue or file size. The “icicle” diagram uses rectangles, while the “sunburst” uses annular segments.

Enclosure diagrams also use an area encoding, but show topology through containment. A treemap recursively subdivides area into rectangles. Circle-packing tightly nests circles; this is not as space-efficient as a treemap, but perhaps more readily shows topology.

A good hierarchical visualization facilitates rapid multiscale inference: micro-observations of individual elements and macro-observations of large groups.

Installing

If you use npm, npm install d3-hierarchy. You can also download the latest release on GitHub. For vanilla HTML in modern browsers, import d3-hierarchy from Skypack:

<script type="module">

import {treemap} from "https://cdn.skypack.dev/d3-hierarchy@3";

const tree = treemap();

</script>

For legacy environments, you can load d3-hierarchy’s UMD bundle from an npm-based CDN such as jsDelivr; a d3 global is exported:

<script src="https://cdn.jsdelivr.net/npm/d3-hierarchy@3"></script>
<script>

const tree = d3.treemap();

</script>

API Reference

Hierarchy

Before you can compute a hierarchical layout, you need a root node. If your data is already in a hierarchical format, such as JSON, you can pass it directly to d3.hierarchy; otherwise, you can rearrange tabular data, such as comma-separated values (CSV), into a hierarchy using d3.stratify.

# d3.hierarchy(data[, children]) · Source, Examples

Constructs a root node from the specified hierarchical data. The specified data must be an object representing the root node. For example:

{
  "name": "Eve",
  "children": [
    {
      "name": "Cain"
    },
    {
      "name": "Seth",
      "children": [
        {
          "name": "Enos"
        },
        {
          "name": "Noam"
        }
      ]
    },
    {
      "name": "Abel"
    },
    {
      "name": "Awan",
      "children": [
        {
          "name": "Enoch"
        }
      ]
    },
    {
      "name": "Azura"
    }
  ]
}

The specified children accessor function is invoked for each datum, starting with the root data, and must return an iterable of data representing the children, if any. If the children accessor is not specified, it defaults to:

function children(d) {
  return d.children;
}

If data is a Map, it is implicitly converted to the entry [undefined, data], and the children accessor instead defaults to:

function children(d) {
  return Array.isArray(d) ? d[1] : null;
}

This allows you to pass the result of d3.group or d3.rollup to d3.hierarchy.

The returned node and each descendant has the following properties:

  • node.data - the associated data, as specified to the constructor.
  • node.depth - zero for the root node, and increasing by one for each descendant generation.
  • node.height - zero for leaf nodes, and the greatest distance from any descendant leaf for internal nodes.
  • node.parent - the parent node, or null for the root node.
  • node.children - an array of child nodes, if any; undefined for leaf nodes.
  • node.value - the summed value of the node and its descendants; optional, see node.sum and node.count.

This method can also be used to test if a node is an instanceof d3.hierarchy and to extend the node prototype.

# node.ancestors() · Source, Examples

Returns the array of ancestors nodes, starting with this node, then followed by each parent up to the root.

# node.descendants() · Source, Examples

Returns the array of descendant nodes, starting with this node, then followed by each child in topological order.

# node.leaves() · Source, Examples

Returns the array of leaf nodes in traversal order; leaves are nodes with no children.

# node.find(filter) · Source

Returns the first node in the hierarchy from this node for which the specified filter returns a truthy value. undefined if no such node is found.

# node.path(target) · Source, Examples

Returns the shortest path through the hierarchy from this node to the specified target node. The path starts at this node, ascends to the least common ancestor of this node and the target node, and then descends to the target node. This is particularly useful for hierarchical edge bundling.

# node.links() · Source, Examples

Returns an array of links for this node and its descendants, where each link is an object that defines source and target properties. The source of each link is the parent node, and the target is a child node.

# node.sum(value) · Source, Examples

Evaluates the specified value function for this node and each descendant in post-order traversal, and returns this node. The node.value property of each node is set to the numeric value returned by the specified function plus the combined value of all children. The function is passed the node’s data, and must return a non-negative number. The value accessor is evaluated for node and every descendant, including internal nodes; if you only want leaf nodes to have internal value, then return zero for any node with children. For example, as an alternative to node.count:

root.sum(function(d) { return d.value ? 1 : 0; });

You must call node.sum or node.count before invoking a hierarchical layout that requires node.value, such as d3.treemap. Since the API supports method chaining, you can invoke node.sum and node.sort before computing the layout, and then subsequently generate an array of all descendant nodes like so:

var treemap = d3.treemap()
    .size([width, height])
    .padding(2);

var nodes = treemap(root
    .sum(function(d) { return d.value; })
    .sort(function(a, b) { return b.height - a.height || b.value - a.value; }))
  .descendants();

This example assumes that the node data has a value field.

# node.count() · Source, Examples

Computes the number of leaves under this node and assigns it to node.value, and similarly for every descendant of node. If this node is a leaf, its count is one. Returns this node. See also node.sum.

# node.sort(compare) · Source, Examples

Sorts the children of this node, if any, and each of this node’s descendants’ children, in pre-order traversal using the specified compare function, and returns this node. The specified function is passed two nodes a and b to compare. If a should be before b, the function must return a value less than zero; if b should be before a, the function must return a value greater than zero; otherwise, the relative order of a and b are not specified. See array.sort for more.

Unlike node.sum, the compare function is passed two nodes rather than two nodes’ data. For example, if the data has a value property, this sorts nodes by the descending aggregate value of the node and all its descendants, as is recommended for circle-packing:

root
    .sum(function(d) { return d.value; })
    .sort(function(a, b) { return b.value - a.value; });
``````

Similarly, to sort nodes by descending height (greatest distance from any descendant leaf) and then descending value, as is recommended for [treemaps](#treemap) and [icicles](#partition):

```js
root
    .sum(function(d) { return d.value; })
    .sort(function(a, b) { return b.height - a.height || b.value - a.value; });

To sort nodes by descending height and then ascending id, as is recommended for trees and dendrograms:

root
    .sum(function(d) { return d.value; })
    .sort(function(a, b) { return b.height - a.height || a.id.localeCompare(b.id); });

You must call node.sort before invoking a hierarchical layout if you want the new sort order to affect the layout; see node.sum for an example.

# node[Symbol.iterator]() <>

Returns an iterator over the node’s descendants in breadth-first order. For example:

for (const descendant of node) {
  console.log(descendant);
}

# node.each(function[, that]) · Source, Examples

Invokes the specified function for node and each descendant in breadth-first order, such that a given node is only visited if all nodes of lesser depth have already been visited, as well as all preceding nodes of the same depth. The specified function is passed the current descendant, the zero-based traversal index, and this node. If that is specified, it is the this context of the callback.

# node.eachAfter(function[, that]) · Source, Examples

Invokes the specified function for node and each descendant in post-order traversal, such that a given node is only visited after all of its descendants have already been visited. The specified function is passed the current descendant, the zero-based traversal index, and this node. If that is specified, it is the this context of the callback.

# node.eachBefore(function[, that]) · Source, Examples

Invokes the specified function for node and each descendant in pre-order traversal, such that a given node is only visited after all of its ancestors have already been visited. The spe

Core symbols most depended-on inside this repo

stratify
called by 38
src/stratify.js
noparent
called by 26
test/stratify-test.js
hierarchy
called by 22
src/hierarchy/index.js
treemap
called by 15
src/treemap/index.js
enclosesWeak
called by 14
test/pack/bench-enclose.js
extendBasis
called by 13
test/pack/bench-enclose.js
encloseBasis
called by 13
test/pack/bench-enclose.js
intersectsAny
called by 10
test/pack/siblings-test.js

Shape

Function 113
Class 2
Method 2

Languages

TypeScript100%

Modules by API surface

test/pack/bench-enclose.js19 symbols
src/tree.js13 symbols
src/pack/enclose.js9 symbols
src/cluster.js8 symbols
test/stratify-test.js7 symbols
src/hierarchy/index.js7 symbols
test/pack/siblings-test.js6 symbols
src/stratify.js6 symbols
src/pack/siblings.js5 symbols
src/pack/index.js5 symbols
test/treemap/index-test.js4 symbols
test/pack/find-place-bugs.js4 symbols

For agents

$ claude mcp add d3-hierarchy \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact