Public
Edited
Apr 25, 2023
Insert cell
md`# Choropleth Mapping
Percentage of Kids in Virginia Counties, Source: [Census 2010]`
Insert cell
d3 = require("d3@5")
Insert cell
import {legend} from "@d3/color-legend"
Insert cell
simple = require("simple-statistics@7.0.7/dist/simple-statistics.min.js")
Insert cell
format = d => `${d}%`
Insert cell
topojson = require("topojson-client@3")
Insert cell
virginia = FileAttachment("Virginia.json").json()
Insert cell
counties = topojson.feature(virginia, virginia.objects.Virginia)
Insert cell
csv_data = d3.csvParse(await FileAttachment("FoodAccessResearchAtlasData2019.csv").text(),({CensusTract, TractKids, Pop2010}) => [CensusTract, +TractKids/+Pop2010])
Insert cell
Insert cell
data = Object.assign(new Map(csv_data), {title: "Percentage of Kids in Virginia's Counties"})
Insert cell
per_kids = Array.from(csv_data.values(), d => d[0])
Insert cell
color = d3.scaleThreshold()
.domain([0.11596505162827642, 0.20150273224043716, 0.2533375715193897, 0.3195299384443201, 0.6])
.range(["#f2f0f7", "#cbc9e2", "#9e9ac8", "#756bb1", "#54278f"])
Insert cell
Insert cell
width = 1000
Insert cell
height = 700
Insert cell
margin = 100
Insert cell
Insert cell
projection = d3.geoTransverseMercator().rotate([82,0]).fitExtent([[80, 80], [width, height]], counties);

Insert cell
path = d3.geoPath().projection(projection);
Insert cell
Insert cell
choropleth = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);

// The following lines of code create the legend in the map by pulling in variables created at the beggining of the code
svg.append("g")
.attr("transform", "translate(360,20)")
.append(() =>
legend({
color: color,
title: data.title,
width: 400,
tickFormat: ".1f"
})
);

svg.append("g")
.selectAll("path")
.data(counties.features)
.join("path")
// The following line of code dictates color of the polygon borders (outlines) in the map by using the attr function
.attr("stroke", "black")
.attr("stroke-linejoin", "round")
.attr("stroke-width", 1)
.attr("fill", d => color(data.get(d.properties.GEOID)))
.attr("d", path)
.append("title")
.text(d => " Percent of Kids: " + data.get(d.properties.GEOID));

return svg.node();
}
Insert cell
Insert cell
Insert cell
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