Published
Edited
Oct 26, 2020
1 fork
Insert cell
md`# Treemap experiment`
Insert cell
data = [
{ name: 'Allen', major: 'Informatics', credits: 107 },
{ name: 'Beth', major: 'Informatics', credits: 19 },
{ name: 'Ruben', major: 'Informatics', credits: 20 },
{ name: 'Stephan', major: 'Math', credits: 20 },
{ name: 'Alice', major: 'Math', credits: 17 }
]
Insert cell
// Group the data
grouped = d3.group(data, d => d.major) // group the data
Insert cell
// Create the hierarchy
hierarchy = d3.hierarchy(grouped).sum(d => d.credits) // create the hierarchy
Insert cell
treemap = d3
.treemap() // function that returns a function!
.size([width, 500]) // set size: d3 takes care of scaling!
.round(true) // Allow rounding of data
.tile(d3.treemapResquarify) // maintain position on transition
.padding(4) // set padding
Insert cell
tm_data = treemap(hierarchy)
Insert cell
tm_data.leaves()
Insert cell
// We'll usually use d3, but we can just use a template literal here
svg`<svg height=500 width = ${width}>
${tm_data.leaves().map(d => {
return `<rect x=${d.x0} y=${d.y0} width=${d.x1 - d.x0} height=${d.y1 -
d.y0} fill=${d.data.major == "Math" ? "red" : "blue"} stroke="white"/>`;
})}
</svg>`
Insert cell
// {
// const data = [
// { name: 'Allen', major: 'Informatics', credits: 17 },
// { name: 'Beth', major: 'Informatics', credits: 19 },
// { name: 'Ruben', major: 'Informatics', credits: 20 },
// { name: 'Stephan', major: 'Math', credits: 20 },
// { name: 'Alice', major: 'Math', credits: 17 }
// ];
// // Group your data into a map
// const grouped = d3.group(data, d => d.major); // group the data
// // Transform into a hierarchy (but don't yet specify the sum() function)
// const hierarchy = d3
// .hierarchy(grouped) // create the hierarchy
// .sum(d => d.credits); // add up the number of credits being taken
// return hierarchy;
// }
Insert cell
d3 = require("d3")
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