Published
Edited
Nov 2, 2020
Fork of Election Map
Importers
5 stars
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([max_value, -max_value], d3.interpolateRdBu)
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
// 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

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