Published
Edited
Nov 5, 2020
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
countyFips = counties2FipsMap.get(selected)
Insert cell
// need to override the chart's color scale because the race/ethnicity by county uses different age buckets than the county totals data
color = d3
.scaleOrdinal()
.domain(ageBuckets)
.range(d3.schemeSpectral[ageBuckets.length])
.unknown("#ccc")
Insert cell
// factory function for returning the stacked data structured required for the chart
getSeries = datum =>
d3
.stack()
.keys(Object.keys(datum))
.offset(d3.stackOffsetExpand)([datum])
.map(d => (d.forEach(v => (v.key = d.key)), d))
Insert cell
// converts our sums arrays into arrays of objects that include keys for age buckets
dataTransformed = {
let transformed = [];

for (let i = 0, l = data.length; i < l; ++i) {
transformed = transformed.concat(
sums[i].reduce((acc, cur, j) => {
acc[ageBuckets[j]] = cur;
return acc;
}, {})
);
}

return transformed;
}
Insert cell
// assert that totals match the sum of sums
totals[0] === d3.sum(sums[0])
Insert cell
totals = data.map(([header, row]) => d3.sum(row.slice(0, -2)))
Insert cell
// this code is pretty stupid, but it works lol
sums = data.map(([header, row], raceIdx) =>
Array.from(variablesList[raceIdx].values(), V =>
d3.sum(V, v => row[indexes[raceIdx].get(v)])
)
)
Insert cell
data = {
let data = [];
for await (let v of variablesList.map(d => fetchData(d, countyFips))) {
yield (data = [...data, v]);
}
}
Insert cell
fetchData = async (variables, fips) => {
const res = await fetch(
`${baseURI}?get=${[...variables.values()]}&for=county:${fips.slice(
2
)}&in=state:${fips.slice(0, 2)}&key=${key}`
);
return await res.json();
}
Insert cell
indexes = data
.map(([header]) => header)
.map(h => new Map(h.map((d, i) => [d, i])))
Insert cell
variablesList = races.map(d => getVariablesMapByRace(d))
Insert cell
races = Array.from(raceGroupCodes.keys())
Insert cell
Insert cell
d3 = require("d3@6")
Insert cell
import { autoSelect } from "@jashkenas/inputs"
Insert cell
import { chart, legend } with {
color
} from "@clhenrick/u-s-county-population-age-distribution"
Insert cell
import {
ageBuckets,
counties2FipsMap,
getVariablesMapByRace,
raceGroupCodes,
baseURI,
key
} from "1c80336c080ed6e9"
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