Public
Edited
Nov 29, 2023
Fork of Choropleth
Insert cell
Insert cell
colorView = html`<input type="color">`
Insert cell
Generators.input(colorView)
Insert cell
chart = {
// Input values from 1 to 5 will be mapped to a color between 1st color and 2nd color.
const domain = [1, 3, 4, 10];
// gradient color stops
const range = ["#FFFFFF", "#FCFCB0", "#58DBF2", "#000000"];

const color = d3
.scaleLinear()
.domain(domain)
.range(range)
.interpolate(d3.interpolateRgb);

const path = d3.geoPath();
const format = (d) => `${d}%`;
const valuemap = new Map(data.map((d) => [d.id, Math.min(d.rate, 10)]));
const counties = topojson.feature(us, us.objects.counties);
const states = topojson.feature(us, us.objects.states);
const statemap = new Map(states.features.map((d) => [d.id, d]));

const statemesh = topojson.mesh(us, us.objects.states, (a, b) => a !== b);

const svg = d3
.create("svg")
.attr("width", 975)
.attr("height", 610)
.attr("viewBox", [0, 0, 975, 610])
.attr("style", "max-width: 100%; height: auto;");

svg
.append("g")
.attr("transform", "translate(610,20)")
.append(() =>
Legend(color, { title: "Unemployment rate (%)", width: 260 })
);
svg
.append("g")
.selectAll("path")
.data(topojson.feature(us, us.objects.counties).features)
.join("path")
.attr("fill", (d) => color(valuemap.get(d.id)))
.attr("d", path)
.append("title")
.text(
(d) =>
`${d.properties.name}, ${
statemap.get(d.id.slice(0, 2)).properties.name
}\n${valuemap.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
data = (await FileAttachment("unemployment-x.csv").csv()).map((d) => (d.rate = +d.rate, d))
Insert cell
us = FileAttachment("counties-albers-10m.json").json() // https://github.com/topojson/us-atlas
Insert cell
import {Legend} from "@d3/color-legend"
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