Published
Edited
Jan 15, 2022
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
turf = require("@turf/turf@6")
Insert cell
import { getWiki } from "@ltrgoddard/utils"
Insert cell
years = [2009, 2013, 2017, 2021]
Insert cell
Insert cell
viewof map = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, 975, 530]);

const projection = d3.geoMercator()
.scale(3e4)
.center(turf
.centroid(boundaries)
.geometry
.coordinates.map((d, i) => i === 1 ? d + .06 : d));

const path = d3.geoPath(projection);

svg.append("g")
.selectAll("path")
.data(boundaries.features)
.join("path")
.attr("fill", d =>
d3.interpolateRgb("white", party_colours.get(swing_to))(
colour(
(vote_share_change
.map(c => ({
constituency: c.constituency.toUpperCase(),
change: c.change}))
.find(c => c.constituency === d.properties.name) || { change: 0 }).change
)
))
.attr("stroke", "grey")
.attr("d", path);
return svg.node();
}
Insert cell
viewof chart = htl.html`<svg width=${width} height=${height}>
<g fill="${party_colours.get(swing_to)}">
${vote_share_change.map(d => htl.svg`<rect y="${y(d.constituency)}" x="${x(0)}" width="${x(d.change)}" height="${y.bandwidth() - 4}"></rect>`)}
</g>
<g fill="white" text-anchor="start" transform="translate(0,${y.bandwidth() / 2})">
${vote_share_change.map(d => htl.svg`<text y="${y(d.constituency)}" x="${x(0)}" font-size="1.2em" font-style="italic" dx=".16em" dy=".23em">${d.constituency}</text>`)}
</g>
<g fill="white" text-anchor="end" transform="translate(0,${y.bandwidth() / 2})">
${vote_share_change.map(d => htl.svg`<text y="${y(d.constituency)}" x="${x(d.change)}" font-size="1.2em" font-style="italic" font-weight="bold" dx="-.2em" dy=".23em">${Math.round(d.change * 100)}</text>`)}
</g>
</svg>`
Insert cell
colour = d3
.scaleLinear()
.domain([d3.min(vote_share_change, d => d.change), d3.max(vote_share_change, d => d.change)])
.range([0, 1])
Insert cell
x = d3
.scaleLinear()
.domain([0, d3.max(vote_share_change, d => d.change)])
.range([0, width])
Insert cell
y = d3
.scaleBand()
.domain(vote_share_change.map(d => d.constituency))
.range([0, height])
Insert cell
// Thanks, Wikipedia! https://en.wikipedia.org/wiki/Wikipedia:Index_of_United_Kingdom_political_parties_meta_attributes
party_colours = new Map([
["Labour", "#E4003B"],
["Conservative", "#0087DC"],
["Liberal Democrats", "#FAA61A"],
["Green", "#6AB023"]
])
Insert cell
height = 260
Insert cell
width = "100%"
Insert cell
Insert cell
boundaries = FileAttachment("CED.geojson")
.json()
.then(d => ({
...d,
features: d.features.filter(f => /SUFFOLK COUNTY$/.test(f.properties.fullname))
}))
Insert cell
target_seats =
d3.flatRollup(
results.filter(d => d.year === 2021),
v => {
const threshold = v[0].seats === 2 ?
d3.sort(v, d => -d.votes)[1].votes :
d3.sort(v, d => -d.votes)[0].votes;
return {
Constituency: v[0].constituency,
Party: d3.sort(v, d => -d.votes)[0].party,
Candidate: d3.sort(v, d => -d.votes)[0].candidate,
Majority: (
d3.min(v
.filter(d => d.party !== swing_to)
.filter(d => d.votes >= threshold)
.map(d => d.votes)) -
d3.max(v
.filter(d => d.party === swing_to)
.filter(d => d.votes < threshold)
.map(d => d.votes))
)
};
},
d => d.constituency)
.map(d => d[1])
Insert cell
vote_share_change =
d3.sort(
d3.rollups(
vote_share,
v =>
(v.find(d => d.year === 2021) || {share: 0}).share -
(v.find(d => d.year === comparison_year) || {share: 0}).share,
d => d.constituency)
.map(d => ({
constituency: d[0],
change: d[1]
})),
d => -d.change)
.filter(d => d.change < Infinity && d.change > 0)
.slice(0, 10)
Insert cell
vote_share =
d3.flatRollup(
results,
v => ({
share:
d3.sum(v.filter(d => swing_to.includes(d.party)), d => d.votes) /
d3.sum(v.filter(d => [...swing_from, ...[swing_to]].includes(d.party)), d => d.votes),
}),
d => d.year,
d => d.constituency)
.map(d => ({
year: d[0],
constituency: d[1],
...d[2]
}))
Insert cell
results =
Promise.all(
years
.map(year => getWiki(`${year}_Suffolk_County_Council_election`)
.then(w => get_results(w)
.map(r => ({year: year, ...r})))))
.then(d => d.flat())
Insert cell
function get_results(wiki) {
return [...wiki.querySelectorAll("table.wikitable.plainrowheaders")]
.map(table => ({
constituency: table.querySelector("caption")
.textContent
.replace(/\(.*\)/g, "")
.replace(/\[.*\]/g, "")
.replace(/ & /g, " and ")
.replace(/^St\./g, "St")
.trim(),
seats: /2/.test(table.querySelector("caption").textContent) ? 2 : 1,
results: [...table.querySelectorAll("tr")]
.map(row => [...row.querySelectorAll("td")]
.map(cell => cell.textContent.trim()))
.filter(row => row.length === 6)
}))
.flatMap(d => d.results
.map(c => ({
constituency: d.constituency,
seats: d.seats,
party: c[1],
candidate: c[2].replace(/ \*$/, ""),
votes: parseInt(c[3].replace(",", ""))
})))
}
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