Public
Edited
Sep 16, 2024
2 forks
Insert cell
Insert cell
chart = CollapsibleTree(data, {
label: d => d.data.name,
title: (d, n) => `${n.ancestors().reverse().map(d => d.data.name).join(".")}`, // hover text
width: 1200,
})
Insert cell
Insert cell
// Using it with d3.group
dynamicTree = CollapsibleTree(
d3.group(
penguins,
(d) => d.species,
(d) => d.island
),
{ label: (d, i) => (Array.isArray(d.data) ? d.data[0] : `🐧`) }
)
Insert cell
howto("CollapsibleTree")
Insert cell
function CollapsibleTree(
data,
{
// data is either tabular (array of objects) or hierarchy (nested objects)
path, // as an alternative to id and parentId, returns an array identifier, imputing internal nodes
id = Array.isArray(data) ? (d) => d.id : null, // if tabular data, given a d in data, returns a unique identifier (string)
parentId = Array.isArray(data) ? (d) => d.parentId : null, // if tabular data, given a node d, returns its parent’s identifier
children, // if hierarchical data, given a d in data, returns its children
tree = d3.tree, // layout algorithm (typically d3.tree or d3.cluster)
sort, // how to sort nodes prior to layout (e.g., (a, b) => d3.descending(a.height, b.height))
label, // given a node d, returns the display name
title, // given a node d, returns its hover text
linkTarget = "_blank", // the target attribute for links (if any)
width = 640, // outer width, in pixels
r = 3, // radius of nodes
padding = 1, // horizontal padding for first and last column
fill = "#999", // fill for nodes
fillOpacity, // fill opacity for nodes
stroke = "#555", // stroke for links
strokeWidth = 1.5, // stroke width for links
strokeOpacity = 0.4, // stroke opacity for links
strokeLinejoin, // stroke line join for links
strokeLinecap, // stroke line cap for links
halo = "#fff", // color of label halo
haloWidth = 3, // padding around the labels
curve = d3.curveBumpX, // curve for the link
transitionDuration = 500 // duration of the transition
} = {}
) {
// If id and parentId options are specified, or the path option, use d3.stratify
// to convert tabular data to a hierarchy; otherwise we assume that the data is
// specified as an object {children} with nested objects (a.k.a. the “flare.json”
// format), and use d3.hierarchy.
const root =
path != null
? d3.stratify().path(path)(data)
: id != null || parentId != null
? d3.stratify().id(id).parentId(parentId)(data)
: d3.hierarchy(data, children);

// Sort the nodes.
if (sort != null) root.sort(sort);

// Compute labels and titles.
const descendants = root.descendants();

const diagonal = d3
.link(curve)
.x((d) => d.y)
.y((d) => d.x);

const margin = { top: 10, right: 120, bottom: 10, left: 40 };
const dx = 10;
const dy = width / (root.height + padding);
const layout = tree().nodeSize([dx, dy]);
layout(root);

root.x0 = dy / 2;
root.y0 = 0;
// Initially collapse everything beyond depth 1
descendants.forEach((d, i) => {
d.id = i;
d._children = d.children;
if (d.depth) d.children = null;
});

// Use the required curve
if (typeof curve !== "function") throw new Error(`Unsupported curve`);

const svg = d3
.create("svg")
.attr("viewBox", [-margin.left, -margin.top, width, dx])
.style("font", "10px sans-serif")
.style("user-select", "none");

const gLink = svg
.append("g")
.attr("fill", "none")
.attr("stroke", stroke)
.attr("stroke-opacity", strokeOpacity)
.attr("stroke-linecap", strokeLinecap)
.attr("stroke-linejoin", strokeLinejoin)
.attr("stroke-width", strokeWidth);

const gNode = svg
.append("g")
.attr("cursor", "pointer")
.attr("pointer-events", "all");

function update(source) {
const duration = d3.event && d3.event.altKey ? 2500 : transitionDuration;
const nodes = root.descendants().reverse();
const links = root.links();

// Compute the new tree layout.
layout(root);

let left = root;
let right = root;
root.eachBefore((node) => {
if (node.x < left.x) left = node;
if (node.x > right.x) right = node;
});

let height = right.x - left.x + dx * 2;

console.log("update", height, dx, left, right);

const transition = svg
.transition()
.duration(duration)
// .attr("viewBox", [-margin.left, left.x - margin.top, width, height])
.attr("viewBox", [(-dy * padding) / 2, left.x - dx, width, height])
.attr("width", width)
.attr("height", height)
// .attr("style", "max-width: 100%; height: auto; height: intrinsic;")
.tween(
"resize",
window.ResizeObserver ? null : () => () => svg.dispatch("toggle")
);

// Update the nodes…
const node = gNode.selectAll("g").data(nodes, (d) => d.id);

// Enter any new nodes at the parent's previous position.
const nodeEnter = node
.enter()
.append("g")
.attr("transform", (d) => `translate(${source.y0},${source.x0})`)
.attr("fill-opacity", 0)
.attr("stroke-opacity", 0)
.on("click", (event, d) => {
d.children = d.children ? null : d._children;
update(d);
});

nodeEnter
.append("circle")
.attr("r", r)
.attr("fill", (d) => (d._children ? stroke : fill))
.attr("stroke-width", 10);

if (label) {
nodeEnter
.append("text")
.attr("dy", "0.31em")
.attr("x", (d) => (d._children ? -6 : 6))
.attr("text-anchor", (d) => (d._children ? "end" : "start"))
.attr("paint-order", "stroke")
.attr("stroke", halo)
.attr("stroke-width", haloWidth)
.text(label);
}

// Transition nodes to their new position.
const nodeUpdate = node
.merge(nodeEnter)
.transition(transition)
.attr("transform", (d) => `translate(${d.y},${d.x})`)
.attr("fill-opacity", 1)
.attr("stroke-opacity", 1);

// Transition exiting nodes to the parent's new position.
const nodeExit = node
.exit()
.transition(transition)
.remove()
.attr("transform", (d) => `translate(${source.y},${source.x})`)
.attr("fill-opacity", 0)
.attr("stroke-opacity", 0);

// Update the links…
const link = gLink.selectAll("path").data(links, (d) => d.target.id);

// Enter any new links at the parent's previous position.
const linkEnter = link
.enter()
.append("path")
.attr("d", (d) => {
const o = { x: source.x0, y: source.y0 };
return diagonal({ source: o, target: o });
});

// Transition links to their new position.
link.merge(linkEnter).transition(transition).attr("d", diagonal);

// Transition exiting nodes to the parent's new position.
link
.exit()
.transition(transition)
.remove()
.attr("d", (d) => {
const o = { x: source.x, y: source.y };
return diagonal({ source: o, target: o });
});

// Stash the old positions for transition.
root.eachBefore((d) => {
d.x0 = d.x;
d.y0 = d.y;
});
}

update(root);

return svg.node();
}
Insert cell
data = FileAttachment("flare.json").json()
Insert cell
import {howto} from "@d3/example-components"
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more