Published
Edited
Jan 21, 2020
Fork of Choropleth
2 forks
Importers
15 stars
Insert cell
Insert cell
chart = {
const path = d3.geoPath();

const svg = d3.create("svg")
.attr("viewBox", "0 0 960 600")
.style("width", "100%")
.style("height", "auto");

svg.append("g")
.attr("transform", "translate(600,40)")
.call(legend);

svg.append("g")
.selectAll("path")
.data(topojson.feature(us, us.objects.counties).features)
.join("path")
.attr("fill", d => color(data.get(d.id)))
.attr("d", path)
.append("title")
.text(d => `${d.properties.name}, ${states.get(d.id.slice(0, 2)).name}
${format(data.get(d.id))}`);

svg.append("path")
.datum(topojson.mesh(us, us.objects.states, (a, b) => a !== b))
.attr("fill", "none")
.attr("stroke", "white")
.attr("stroke-linejoin", "round")
.attr("d", path);

return svg.node();
}
Insert cell
legend = g => {
const width = 240;

g.append("image")
.attr("width", width)
.attr("height", 8)
.attr("preserveAspectRatio", "none")
.attr("xlink:href", ramp(color.interpolator()).toDataURL());

g.append("text")
.attr("class", "caption")
.attr("y", -6)
.attr("fill", "#000")
.attr("text-anchor", "start")
.attr("font-weight", "bold")
.text(data.title);

g.call(d3.axisBottom(d3.scaleLinear(color.domain(), [0, width / 2, width]))
.ticks(6)
.tickFormat(d => `${d > 0 ? "+" : ""}${(d * 100).toFixed(0)}`)
.tickSize(13))
.select(".domain")
.remove();
}
Insert cell
data = Object.assign(new Map(d3.zip(...await Promise.all([10, 11].map(fetchPopulation))).map(([[id2017, population2017], [id2018, population2018]]) => {
if (id2017 !== id2018) throw new Error;
return [id2017, Math.round((population2018 - population2017) / population2017 * 1000) / 1000];
})), {title: "Population change (%)"})
Insert cell
function fetchPopulation(date) {
return d3.json("https://api.census.gov/data/2018/pep/population?get=POP&for=county:*&DATE_CODE=" + date).then(rows => rows.slice(1).sort((a, b) => d3.ascending(a[2], b[2]) || d3.ascending(a[3], b[3])).map(([population,, state, county]) => [state + county, +population]));
}
Insert cell
color = d3.scaleDiverging([-0.03, 0, 0.03], d3.interpolateRdBu)
Insert cell
format = d3.format("+.1%")
Insert cell
states = new Map(us.objects.states.geometries.map(d => [d.id, d.properties]))
Insert cell
us = FileAttachment("counties-albers-10m.json").json()
Insert cell
topojson = require("topojson-client@3")
Insert cell
d3 = require("d3@5")
Insert cell
import {ramp} from "@mbostock/color-ramp"
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more