Public
Edited
Sep 3, 2023
Insert cell
Insert cell
import {Tree} from "@d3/tree";

Insert cell
tree = (data, options = {}) => {
const _options = {
breadthOffset: 10, // vertical offset between nodes.
depthOffset: undefined, // horizontal offset between nodes.
minHeight: 0,
...options,
}
const root = d3.hierarchy(data)
root.dx = _options.breadthOffset
root.dy = _options.depthOffset || width / Math.max((root.height + 1), _options.minHeight)
return d3.tree().nodeSize([root.dx, root.dy])(root)
}
Insert cell
data = FileAttachment("characters.json").json()

Insert cell
chartIndented = {
const breadthOffset = 16
const depthOffset = 16
const root = tree(data, { depthOffset, breadthOffset: 10 })
let index = 0
root.eachBefore(d => {
d.x = index * breadthOffset
index += 1
})

let x0 = Infinity
let x1 = -x0
root.each(d => {
if (d.x > x1) x1 = d.x
if (d.x < x0) x0 = d.x
})

const svg = d3
.select(DOM.svg(width, x1 - x0 + root.dx * 2))
.style("width", "100%")
.style("height", "auto")

const g = svg
.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.attr("transform", `translate(${root.dy / 3}, ${root.dx - x0})`)
const linkShape = d => `M${d.source.y},${d.source.x}V${d.target.x}H${d.target.y}`

const link = g
.append("g")
.attr("fill", "none")
.attr("stroke", "#ccc")
.attr("stroke-opacity", 1)
.attr("stroke-width", 1.5)
.selectAll("path")
.data(root.links())
.join("path")
.attr("d", linkShape)

const node = g
.append("g")
.attr("stroke-linejoin", "round")
.attr("stroke-width", 3)
.selectAll("g")
.data(root.descendants())
.join("g")
.attr("transform", d => `translate(${d.y}, ${d.x})`)

node
.append("circle")
.attr("fill", d => (d.children ? "#555" : "#999"))
.attr("r", 2.5)

node
.append("text")
.attr("dy", "0.31em")
.attr("x", d => (d.children ? 6 : 6))
.attr("text-anchor", d => (d.children ? "start" : "start"))
.text(d => d.data.name.toLowerCase())
.clone(true)
.lower()
.attr("stroke", "white")

return svg.node()
}

Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more