Published
Edited
May 6, 2021
1 star
Insert cell
Insert cell
Insert cell
// Load data
data = d3.csv("https://projects.fivethirtyeight.com/2020-general-data/presidential_state_toplines_2020.csv")
Insert cell
// Filter down to most recent, grab columns of interest
most_recent = aq.from(data)
.filter(d => d.modeldate == "11/2/2020")
.select("state", "margin")
.objects()
Insert cell
// Represent as a Map object to more easily access the values for each state
most_recent_obj = new Map(most_recent.map(d => [d.state, +d.margin]))
Insert cell
// Create a diverging color scale
color = d3.scaleSequential([40, -40], d3.interpolateRdYlBu)
Insert cell
d3.interpolateRdYlBu
Insert cell
color_legend = legend({color:color, title:"Margin of Victory"})
Insert cell
max_value = d3.max(most_recent, d => Math.abs(+d.margin))
Insert cell
Insert cell
// Load shapefile
shapefile = d3.json("https://cdn.jsdelivr.net/npm/us-atlas@3/states-albers-10m.json")
Insert cell
// Create a path drawing function
path = d3.geoPath()
Insert cell
Insert cell
import { nest } from "@bayre/unrolling-a-d3-rollup"
Insert cell
pop_data = d3.csv(
await FileAttachment("countypres_2000-2016.csv").url(),
d3.autoType
)
Insert cell
pop_data_2016 = pop_data.filter(d => d.year == 2016)
Insert cell
Insert cell
// Let's make a map!
map = {
// Create the svg
const svg = d3.create("svg")
.attr("width", width)
.attr("height", 600)
.style("text-anchor", "middle")
.style('font-family', 'sans-serif')
.style("font-size", "12px")
// Add paths for each state
const paths = svg.selectAll("path")
.data(topojson.feature(shapefile, shapefile.objects.states).features)
.join("path")
.attr("d", path)
.attr("fill", d => {
return color(most_recent_obj.get(d.properties.name))
})
// Add text for each state
const labels = svg.selectAll("text")
.data(topojson.feature(shapefile, shapefile.objects.states).features)
.join("text")
.text(d => most_recent_obj.get(d.properties.name).toFixed(1))
.attr("y", d => path.centroid(d)[1])
.attr("x", d => path.centroid(d)[0])
// Add a title
const title = svg.append("text")
.attr('x', width/2)
.attr("y", 20)
.text("Presidential Forecast")
.style("font-size", "20px")

// Add a legend
svg.append("g")
.attr("transform", `translate(${width - 300}, 5)`)
.append(() => color_legend)
// Return svg
return svg.node()
}
Insert cell
topojson.feature(shapefile, shapefile.objects.states).features
Insert cell
Insert cell
d3 = require("d3")
Insert cell
import { aq, op } from "@uwdata/arquero"
Insert cell
topojson = require("topojson-client@3")
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