Published
Edited
Sep 11, 2020
1 star
Insert cell
Changed in fork
-
md`# Treemap
+
md`# Tidy treemap
-
Introduced by [Ben Shneiderman](http://www.cs.umd.edu/hcil/treemap-history/), treemaps recursively partition space into rectangles according to each node’s associated value. D3 supports several treemap tiling methods. See also [nested](/@d3/nested-treemap), [zoomable](/@d3/zoomable-treemap) and [animated](/@d3/animated-treemap) treemaps.`
+
This treemap accommodates [tidy data](https://vita.had.co.nz/papers/tidy-data.pdf). It uses [d3.rollup](/@d3/d3-group) to build a hierarchy so you don't have to. Data on cobalt exports in 2018 from [resourcetrade.earth](https://resourcetrade.earth/data?year=2018&category=178&units=value).`
Insert cell
Insert cell
Changed in fork
chart = { const root = treemap(data); const svg = d3.create("svg") .attr("viewBox", [0, 0, width, height]) .style("font", "10px sans-serif"); const leaf = svg.selectAll("g") .data(root.leaves()) .join("g") .attr("transform", d => `translate(${d.x0},${d.y0})`); leaf.append("title")
-
.text(d => `${d.ancestors().reverse().map(d => d.data.name).join("/")}\n${format(d.value)}`);
+
.text(d => `${d.ancestors().reverse().map(d => d.data[0]).join("/")}\n${format(d.value)}`);
leaf.append("rect") .attr("id", d => (d.leafUid = DOM.uid("leaf")).id)
-
.attr("fill", d => { while (d.depth > 1) d = d.parent; return color(d.data.name); })
+
.attr("fill", d => { while (d.depth > 1) d = d.parent; return color(d.data[0]); })
.attr("fill-opacity", 0.6) .attr("width", d => d.x1 - d.x0) .attr("height", d => d.y1 - d.y0); leaf.append("clipPath") .attr("id", d => (d.clipUid = DOM.uid("clip")).id) .append("use") .attr("xlink:href", d => d.leafUid.href); leaf.append("text") .attr("clip-path", d => d.clipUid) .selectAll("tspan")
-
.data(d => d.data.name.split(/(?=[A-Z][a-z])|\s+/g).concat(format(d.value)))
+
.data(d => d.data[0].split(/(?=[A-Z][a-z])|\s+/g).concat(format(d.value)))
.join("tspan") .attr("x", 3) .attr("y", (d, i, nodes) => `${(i === nodes.length - 1) * 0.3 + 1.1 + i * 0.9}em`) .attr("fill-opacity", (d, i, nodes) => i === nodes.length - 1 ? 0.7 : null) .text(d => d); return svg.node(); }
Insert cell
Added in fork
data = FileAttachment("cobalt.csv").csv({typed: true})
Insert cell
Added in fork
keys = data.columns.slice(0, -1)
Insert cell
Added in fork
value = data.columns.slice(-1)
Insert cell
Removed in fork
data = FileAttachment("flare-2.json").json()
Insert cell
Changed in fork
treemap = data => d3.treemap() .tile(tile) .size([width, height]) .padding(1) .round(true)
-
(d3.hierarchy(data) .sum(d => d.value)
+
(d3.hierarchy(d3.rollup(data, ([v]) => v[value], ...keys.map(k => d => d[k]))) .sum(([,d]) => d)
.sort((a, b) => b.value - a.value))
Insert cell
width = 954
Insert cell
height = 954
Insert cell
Changed in fork
-
format = d3.format(",d")
+
format = d3.format(".3s")
Insert cell
color = d3.scaleOrdinal(d3.schemeCategory10)
Insert cell
d3 = require("d3@6")
Insert cell