D3.js V3迁移至V4:.value、.sort及bundle布局替代方案咨询
Hey there! I totally get the frustration when jumping between D3 versions—v4 made some big API overhauls, especially shifting layouts to revolve around the hierarchy system. Let's break down how to adapt your code step by step:
1. Replacing .sort() and .value() for the Cluster Layout
In v3, the cluster layout handled sorting and value calculation directly. In v4, these jobs move to the hierarchy data structure that feeds into the cluster layout. Here's the fix:
- Sorting: Instead of chaining
.sort()to the cluster layout, create a hierarchy from your data first, then call.sort()on that hierarchy. - Value calculation: The old
.value()method is replaced by.sum()on the hierarchy, which computes aggregated values for each node (like yourd.size).
2. Replacing d3.layout.bundle()
The bundle layout got a simple namespace shift in v4—it's now just d3.bundle(). Its usage also adjusted slightly: it takes the links from your hierarchy and returns the bundled path data directly.
Full Adapted v4 Code
Here's your original v3 code translated to v4, with comments calling out the changes:
// First, wrap your data in a hierarchy structure (replace `data` with your actual dataset) const root = d3.hierarchy(data) // Replace v3's cluster.sort() with hierarchy.sort() .sort(function(a, b) { return d3.descending(a.key, b.key); }) // Replace v3's cluster.value() with hierarchy.sum() .sum(function(d) { return d.size; }); // Initialize the cluster layout (v4 uses d3.cluster() instead of d3.layout.cluster()) const cluster = d3.cluster() .size([360, innerRadius]) // Separation method works the same as v3—no changes needed here .separation(function separation(a, b) { return (a.parent == b.parent ? 1 : 1.2) / a.depth; }); // Run the cluster layout on your hierarchy cluster(root); // Replace d3.layout.bundle() with d3.bundle() const bundle = d3.bundle(); // Use it with the links array from your processed hierarchy const bundledLinks = bundle(root.links());
Quick Key Reminders
- v4 layouts like
clusterdon't take raw data directly—you must wrap your dataset in ad3.hierarchyfirst. - The hierarchy object now handles data aggregation (
.sum()) and sorting (.sort()), which were previously part of the cluster layout itself. d3.bundle()operates on the links array from your hierarchy (root.links()) instead of raw link data you might have used in v3.
内容的提问来源于stack exchange,提问作者ThePanxos

