d3.link() is a D3 shape generator for drawing paths between source and target points. In a tree chart, it converts each link into an SVG path’s d attribute. section 11.3.2
Build a tree-link generator by:
- Importing link() and a curve such as curveBumpX from d3-shape. section 11.3.2
- Passing the curve to link() and mapping x and y accessors to the tree layout’s coordinates. section 11.3.2
- Binding root.links() to path elements and assigning each generated path to d. section 11.3.2
Listing 11.16 Drawing the links (tree.js)
...
import { select } from "d3-selection";
import { link, curveBumpX } from "d3-shape";
export const drawTree = (root, descendants) => {
...
const svg = select("#tree") #1
.append("svg")
.attr("viewBox", `0 0 ${width} ${height}`)
.append("g")
.attr("transform", `translate(${margin.left},
${margin.top})`);
const linkGenerator = link(curveBumpX) #2
.x(d => d.y)
.y(d => d.x);
svg #3
.selectAll(".tree-link")
.data(root.links())
.join("path")
.attr("class", "tree-link")
.attr("d", d => linkGenerator(d))
.attr("fill", "none")
.attr("stroke", "gray")
.attr("stroke-opacity", 0.6);
};
The complete pattern imports the generator, configures curve and coordinate accessors, then styles data-bound tree links. section 11.3.2
