|
| 1 | +<!doctype html> |
| 2 | +<notebook theme="air"> |
| 3 | + <title>Animated treemap</title> |
| 4 | + <script id="5" type="text/markdown"> |
| 5 | + # Animated treemap |
| 6 | + |
| 7 | + This [treemap](./treemap) of U.S. population uses [d3.treemapResquarify](https://d3js.org/d3-hierarchy/treemap#treemapResquarify) for a stable layout with changing node values. Data: [U.S. Census Bureau](https://www.census.gov/population/www/censusdata/pop1790-1990.html) |
| 8 | + </script> |
| 9 | + <script id="6" type="module"> |
| 10 | + const input = Scrubber(d3.range(data.keys.length), { |
| 11 | + delay: 2500, |
| 12 | + loop: false, |
| 13 | + format: (i) => data.keys[i] |
| 14 | + }); |
| 15 | + const index = view(input); |
| 16 | + </script> |
| 17 | + <script id="1" type="module" pinned=""> |
| 18 | + const width = 928; |
| 19 | + const height = width; |
| 20 | + |
| 21 | + // This is normally zero, but could be non-zero if this cell is |
| 22 | + // re-evaluated after the animation plays. |
| 23 | + const initialIndex = input.value; |
| 24 | + |
| 25 | + // To allow the transition to be interrupted and resumed, we parse |
| 26 | + // the displayed text (the state population) to get the current |
| 27 | + // value at the start of each transition; parseNumber and |
| 28 | + // formatNumber must be symmetric. |
| 29 | + const parseNumber = (string) => +string.replace(/,/g, ""); |
| 30 | + const formatNumber = d3.format(",d"); |
| 31 | + |
| 32 | + // Get the maximum total population across the dataset. (We know |
| 33 | + // for this dataset that it’s always the last value, but that isn’t |
| 34 | + // true in general.) This allows us to scale the rectangles for |
| 35 | + // each state to be proportional to the max total. |
| 36 | + const max = d3.max(data.keys, (d, i) => d3.hierarchy(data.group).sum((d) => d.values[i]).value); |
| 37 | + |
| 38 | + // The category10 color scheme per state, but faded so that the |
| 39 | + // text labels are more easily read. |
| 40 | + const color = d3.scaleOrdinal() |
| 41 | + .domain(data.group.keys()) |
| 42 | + .range(d3.schemeCategory10.map((d) => d3.interpolateRgb(d, "white")(0.5))); |
| 43 | + |
| 44 | + // Construct the treemap layout. |
| 45 | + const treemap = d3.treemap() |
| 46 | + .size([width, height]) |
| 47 | + .tile(d3.treemapResquarify) // to preserve orientation when animating |
| 48 | + .padding((d) => d.height === 1 ? 1 : 0) // only pad parents of leaves |
| 49 | + .round(true); |
| 50 | + |
| 51 | + // Compute the structure using the average value (since this |
| 52 | + // orientation will be preserved using resquarify across the |
| 53 | + // entire animation). |
| 54 | + const root = treemap(d3.hierarchy(data.group) |
| 55 | + .sum((d) => Array.isArray(d.values) ? d3.sum(d.values) : 0) |
| 56 | + .sort((a, b) => b.value - a.value)); |
| 57 | + |
| 58 | + const svg = d3.create("svg") |
| 59 | + .attr("width", width) |
| 60 | + .attr("height", height + 20) |
| 61 | + .attr("viewBox", [0, -20, width, height + 20]) |
| 62 | + .attr("style", "max-width: 100%; height: auto; font: 10px sans-serif; overflow: visible;"); |
| 63 | + |
| 64 | + // Draw a box representing the total population for each time. Only |
| 65 | + // show the boxes after the current time (to avoid distracting gray |
| 66 | + // lines in between the padded treemap cells). |
| 67 | + const box = svg.append("g") |
| 68 | + .selectAll("g") |
| 69 | + .data(data.keys.map((key, i) => { |
| 70 | + const value = root.sum((d) => d.values[i]).value; |
| 71 | + return {key, value, i, k: Math.sqrt(value / max)}; |
| 72 | + }).reverse()) |
| 73 | + .join("g") |
| 74 | + .attr("transform", ({k}) => `translate(${(1 - k) / 2 * width},${(1 - k) / 2 * height})`) |
| 75 | + .attr("opacity", ({i}) => i >= initialIndex ? 1 : 0) |
| 76 | + .call((g) => g.append("text") |
| 77 | + .attr("y", -6) |
| 78 | + .attr("fill", "#777") |
| 79 | + .selectAll("tspan") |
| 80 | + .data(({key, value}) => [key, ` ${formatNumber(value)}`]) |
| 81 | + .join("tspan") |
| 82 | + .attr("font-weight", (d, i) => i === 0 ? "bold" : null) |
| 83 | + .text((d) => d)) |
| 84 | + .call((g) => g.append("rect") |
| 85 | + .attr("fill", "none") |
| 86 | + .attr("stroke", "#ccc") |
| 87 | + .attr("width", ({k}) => k * width) |
| 88 | + .attr("height", ({k}) => k * height)); |
| 89 | + |
| 90 | + // Render the leaf nodes of the treemap. |
| 91 | + const leaf = svg.append("g") |
| 92 | + .selectAll("g") |
| 93 | + .data(layout(initialIndex)) |
| 94 | + .join("g") |
| 95 | + .attr("transform", (d) => `translate(${d.x0},${d.y0})`); |
| 96 | + |
| 97 | + leaf.append("rect") |
| 98 | + .attr("id", (d, i) => (d.leafUid = `leaf-${i}`)) |
| 99 | + .attr("fill", (d) => { while (d.depth > 1) d = d.parent; return color(d.data[0]); }) |
| 100 | + .attr("width", (d) => d.x1 - d.x0) |
| 101 | + .attr("height", (d) => d.y1 - d.y0); |
| 102 | + |
| 103 | + // Clip the text to the containing node. |
| 104 | + leaf.append("clipPath") |
| 105 | + .attr("id", (d, i) => (d.clipUid = `clip-${i}`)) |
| 106 | + .append("use") |
| 107 | + .attr("xlink:href", (d) => `#${d.leafUid}`); |
| 108 | + |
| 109 | + // Generate two tspans for two lines of text (name and value). |
| 110 | + const text = leaf.append("text") |
| 111 | + .attr("clip-path", (d) => `url(#${d.clipUid})`); |
| 112 | + |
| 113 | + // Safari clipping bug: https://observablehq.com/d/ff34268ca0f9e2b5 |
| 114 | + text.append("tspan") |
| 115 | + .text("\xa0"); |
| 116 | + |
| 117 | + text.append("tspan") |
| 118 | + .attr("x", 3) |
| 119 | + .attr("y", "1.1em") |
| 120 | + .text((d) => d.data.name); |
| 121 | + |
| 122 | + text.append("tspan") |
| 123 | + .attr("x", 3) |
| 124 | + .attr("y", `${1.1 + 1.2}em`) |
| 125 | + .attr("fill-opacity", 0.7) |
| 126 | + .text((d) => formatNumber(d.value)); |
| 127 | + |
| 128 | + leaf.append("title") |
| 129 | + .text((d) => d.data.name); |
| 130 | + |
| 131 | + display(svg.node()); |
| 132 | + |
| 133 | + // Scale the treemap layout to fit within a centered box whose area |
| 134 | + // is proportional to the total current value. This makes the areas |
| 135 | + // of each state proportional for the entire animation. |
| 136 | + function layout(index) { |
| 137 | + const k = Math.sqrt(root.sum((d) => d.values[index]).value / max); |
| 138 | + const tx = (1 - k) / 2 * width; |
| 139 | + const ty = (1 - k) / 2 * height; |
| 140 | + return treemap.size([width * k, height * k])(root) |
| 141 | + .each((d) => (d.x0 += tx, d.x1 += tx, d.y0 += ty, d.y1 += ty)) |
| 142 | + .leaves(); |
| 143 | + } |
| 144 | + |
| 145 | + // Expose an update method on the chart that allows the caller to |
| 146 | + // initiate a transition. The given index represents the frame |
| 147 | + // number (0 for the first frame, 1 for the second, etc.). |
| 148 | + function update(index, duration) { |
| 149 | + box.transition() |
| 150 | + .duration(duration) |
| 151 | + .attr("opacity", ({i}) => i >= index ? 1 : 0); |
| 152 | + |
| 153 | + leaf.data(layout(index)).transition() |
| 154 | + .duration(duration) |
| 155 | + .ease(d3.easeLinear) |
| 156 | + .attr("transform", (d) => `translate(${d.x0},${d.y0})`) |
| 157 | + .call((leaf) => leaf.select("rect") |
| 158 | + .attr("width", (d) => d.x1 - d.x0) |
| 159 | + .attr("height", (d) => d.y1 - d.y0)) |
| 160 | + .call((leaf) => leaf.select("text tspan:last-child") |
| 161 | + .tween("text", function(d) { |
| 162 | + const i = d3.interpolate(parseNumber(this.textContent), d.value); |
| 163 | + return function(t) { this.textContent = formatNumber(i(t)); }; |
| 164 | + })); |
| 165 | + } |
| 166 | + </script> |
| 167 | + <script id="4" type="module" pinned=""> |
| 168 | + update(index, 2500); // trigger animation from the scrubber |
| 169 | + </script> |
| 170 | + <script id="3" type="module" pinned=""> |
| 171 | + const keys = d3.range(1790, 2000, 10); |
| 172 | + const [regions, states] = await Promise.all([ |
| 173 | + FileAttachment("data/census-regions.csv").csv(), // for grouping states hierarchically |
| 174 | + FileAttachment("data/population.tsv").tsv() // a wide dataset of state populations over time |
| 175 | + ]).then(([regions, states]) => [ |
| 176 | + regions, |
| 177 | + states.slice(1).map((d) => ({ |
| 178 | + name: d[""], // the state name |
| 179 | + values: keys.map((key) => +d[key].replace(/,/g, "")) // parse comma-separated numbers |
| 180 | + })) |
| 181 | + ]); |
| 182 | + const regionByState = new Map(regions.map((d) => [d.State, d.Region])); |
| 183 | + const divisionByState = new Map(regions.map((d) => [d.State, d.Division])); |
| 184 | + const data = display({keys, group: d3.group(states, (d) => regionByState.get(d.name), (d) => divisionByState.get(d.name))}); |
| 185 | + </script> |
| 186 | + <script id="2" type="module" pinned=""> |
| 187 | + import {Scrubber} from "./scrubber.js"; |
| 188 | + </script> |
| 189 | +</notebook> |
0 commit comments