Public
Edited
Nov 8, 2022
Insert cell
Insert cell
data = [
{instance: 1, fi: 0, cf:0 },
{instance: 2, fi: 0, cf:0 },
{instance: 3, fi: 1, cf:0 },
{instance: 4, fi: 1, cf:0 },
{instance: 5, fi: 0, cf:0 },
{instance: 6, fi: 1, cf:0 },
{instance: 7, fi: 1, cf:0 },
{instance: 8, fi: 0, cf:0 },
]
Insert cell
Insert cell
group = d3.group(data, d => d.nation, d => d.sport)
Insert cell
Insert cell
hierarchy = d3.hierarchy(group)
Insert cell
Insert cell
hierarchy.height
Insert cell
hierarchy.data // root, has the undefined key
Insert cell
hierarchy.children[0].data // nation
Insert cell
hierarchy.children[0].children[0].data // sport
Insert cell
hierarchy.children[0].children[0].children[0].data // athlete
Insert cell
Insert cell
md`${hierarchy.descendants().map(
d => `${"> ".repeat(d.depth)} ${d.data[0] || d.data["name"] || "root"} / \n`
)}`
Insert cell
Insert cell
hierarchy.count().value // count athletes in the hierarchy; equal to the original data.length
Insert cell
sums = hierarchy.copy().sum(d => d.earnings)
Insert cell
sums.value // total earnings, equal to d3.sum(data, d => d.earnings)
Insert cell
sums.find(d => d.data[0] === "United States").value // total earnings of athletes in the US
Insert cell
Insert cell
hierarchy.leaves().map(d => d.data)
Insert cell
Insert cell
Soccer = hierarchy.find(d => d.data[0] === "Soccer")
Insert cell
Federer = hierarchy.find(d => d.data.name === "Roger Federer")
Insert cell
Soccer.path(Federer).map(d => d.data[0] || d.data.name || "^root")
Insert cell
Insert cell
hierarchy.copy().sort((a, b) => d3.ascending(a.data[0], b.data[0])).children.map(d => d.data[0])
Insert cell
Insert cell
rollup = d3.rollup(
data,
v => d3.sum(v, d => d.earnings),
d => d.nation,
d => d.sport
)
Insert cell
R = d3.hierarchy(rollup)
Insert cell
Insert cell
R.leaves().map(d => [d.parent.data[0], ">", ...d.data].join(" "))
Insert cell
Insert cell
{
const names = [];
R.copy().sum(d => d[1]).eachBefore((d, index) =>
names.push(" ".repeat(d.depth) + `${d.depth}: ${d.data[0] || "All"}, ${d.value} (${index})`)
);
return html`<pre style="max-height: 15em; overflow-y: scroll;">${names.join(
"\n"
)}`;
}
Insert cell
Insert cell
{
const names = [];
R.copy().sum(d => d[1]).eachAfter((d, i) =>
names.push(" ".repeat(d.depth) + `${d.depth}: ${d.data[0] || "All"}, ${d.value} (${i})`)
);
return html`<pre style="max-height: 15em; overflow-y: scroll;">${names.join(
"\n"
)}`;
}
Insert cell
Insert cell
Insert cell
d3.median(hierarchy, d => d.data.earnings)
Insert cell
d3.extent(hierarchy, d => d.children && d.children.length)
Insert cell
Insert cell
d3 = require("d3@6")
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