Published
Edited
Feb 6, 2019
2 forks
14 stars
Insert cell
Insert cell
Insert cell
Insert cell
chart = {
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");

svg.append("defs").html(`
<style>
.highlight circle { fill:pink }
.highlight circle { fill:pink }
.highlight text { fill:pink }
.leaf circle { fill:red }
.leaf circle { fill:red }
.leaf text { fill:red }
path.highlight { stroke:pink }
<style>`);

const g = svg
.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.attr("transform", `translate(${root.dy / 3},${root.dx - x0})`);

const link = g
.append("g")
.attr("fill", "none")
.attr("stroke", "#555")
.attr("stroke-opacity", 0.4)
.attr("stroke-width", 1.5)
.selectAll("path")
.data(root.links())
.join("path")
.attr(
"d",
d3
.linkHorizontal()
.x(d => d.y)
.y(d => d.x)
);

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 ? "end" : "start"))
.text(d => d.data.name)
.clone(true)
.lower()
.attr("stroke", "white");

function dist2(a, b) {
return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2;
}
g.on("mousemove", function() {
const m = d3.mouse(this);
const leaf = node.data()[
d3.scan(node.data().map(d => dist2([d.y, d.x], m)))
];

let d = root
.links()
.filter(d => d.target === leaf)
.pop().target;
const path = [];

do {
path.push(d.data);
} while ((d = d.parent));

node.classed("highlight", d => path.indexOf(d.data) > -1);
node.classed("leaf", d => path.indexOf(d.data) === 0);
link.classed("highlight", d => path.indexOf(d.target.data) > -1);

svg.node().value = path;
svg.node().dispatchEvent(new CustomEvent("input"));
});

return svg.node();
}
Insert cell
data = require("@observablehq/flare")
Insert cell
tree = data => {
const root = d3.hierarchy(data);
root.dx = 10;
root.dy = width / (root.height + 1);
return d3.tree().nodeSize([root.dx, root.dy])(root);
}
Insert cell
Insert cell
width = 932
Insert cell
d3 = require("d3@^5.8")
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