UK Constituency Explorer
  • Hex Map
  • Geographic Map
  • Scatterplot
  • Histogram
  • Box Plot
  • Heatmap
  • Constituency Profile
  • Data Table

Heatmap

rawData = FileAttachment("data/constituencies.json").json()

partyColors = ({
  "Con": "#0087DC", "Lab": "#DC241f", "LD": "#FAA61A",
  "Green": "#6AB023", "RUK": "#12B6CF", "SNP": "#FDF38E",
  "PC": "#005B54", "Ind": "#999999", "Other": "#AAAAAA"
})

allVarsMap = [
  {label: "Conservative 2024",       value: "Con24"},
  {label: "Labour 2024",             value: "Lab24"},
  {label: "Lib Dem 2024",            value: "LD24"},
  {label: "Reform 2024",             value: "RUK24"},
  {label: "Green 2024",              value: "Green24"},
  {label: "SNP 2024",                value: "SNP24"},
  {label: "Plaid Cymru 2024",        value: "PC24"},
  {label: "Other 2024",              value: "Other24"},
  {label: "Conservative 2019",       value: "Con19"},
  {label: "Labour 2019",             value: "Lab19"},
  {label: "Lib Dem 2019",            value: "LD19"},
  {label: "Reform/Brexit 2019",      value: "Brexit19"},
  {label: "Green 2019",              value: "Green19"},
  {label: "SNP 2019",                value: "SNP19"},
  {label: "Plaid Cymru 2019",        value: "PC19"},
  {label: "Turnout 2024",            value: "Turnout24"},
  {label: "Turnout 2019",            value: "Turnout19"},
  {label: "Majority 2024",           value: "Majority24"},
  {label: "Brexit Leave (Hanretty)", value: "HanrettyLeave"},
  {label: "Population Density",      value: "c21PopulationDensity"},
  {label: "Age: Under 15",           value: "AgeUnder15"},
  {label: "Age: 16-24",              value: "Age16to24"},
  {label: "Age: 25-34",              value: "Age25to34"},
  {label: "Age: 35-44",              value: "Age35to44"},
  {label: "Age: 45-54",              value: "Age45to54"},
  {label: "Age: 55-64",              value: "Age55to64"},
  {label: "Age: Over 65",            value: "AgeOver65"},
  {label: "Ethnicity: White",        value: "c21EthnicityWhite"},
  {label: "Ethnicity: Asian",        value: "c21EthnicityAsian"},
  {label: "Ethnicity: Black",        value: "c21EthnicityBlack"},
  {label: "Ethnicity: Mixed",        value: "c21EthnicityMixed"},
  {label: "Born in UK",              value: "born_uk"},
  {label: "Religion: Christian",     value: "c21Christian"},
  {label: "Religion: Muslim",        value: "c21Muslim"},
  {label: "Religion: No Religion",   value: "c21NoReligion"},
  {label: "Qualification: None",     value: "c21QualNone"},
  {label: "Qualification: Level 4+", value: "c21QualLevel4"},
  {label: "Housing: Owned Outright", value: "c21HouseOutright"},
  {label: "Housing: Mortgage",       value: "c21HouseMortgage"},
  {label: "Housing: Social Rent",    value: "c21HouseSocialLA"},
  {label: "Housing: Private Rent",   value: "c21HousePrivateLandlord"},
  {label: "No Car",                  value: "c21CarsNone"},
  {label: "Health: Very Good",       value: "c21HealthVeryGood"},
  {label: "Health: Bad/Very Bad",    value: "c21HealthBad"},
  {label: "Employment: Unemployed",  value: "c21Unemployed"},
  {label: "Deprivation: None",       value: "c21DeprivedNone"},
  {label: "Deprivation: 3+ dims",    value: "c21Deprived3"}
]

mapVarsMap = [
  {label: "2024 Winner", value: "Winner24"},
  {label: "2019 Winner", value: "Winner19"},
  ...allVarsMap
]

allVarLabels = Object.fromEntries(allVarsMap.map(v => [v.value, v.label]))
mapVarLabels = Object.fromEntries(mapVarsMap.map(v => [v.value, v.label]))
allRegions   = [...new Set(rawData.map(d => d.Region))].filter(Boolean).sort()
allWinners   = [...new Set(rawData.map(d => d.Winner24))].filter(Boolean).sort()
allConsts    = rawData.map(d => d.ConstituencyName).filter(Boolean).sort()
defaultHeatVars = ["Con24","Lab24","LD24","RUK24","Green24","HanrettyLeave",
  "c21QualLevel4","c21QualNone","AgeOver65","Age25to34",
  "c21EthnicityWhite","c21HousePrivateLandlord","c21PopulationDensity"]
viewof heatVars = Inputs.select(
  new Map(allVarsMap.map(v => [v.label, v.value])),
  {label: "Variables:", multiple: true, value: defaultHeatVars, size: 16}
)

Region:

viewof heatRegions = Inputs.checkbox(allRegions, {value: allRegions})

2024 Winner:

viewof heatWinners = Inputs.checkbox(allWinners, {value: allWinners})
filteredHeat = rawData.filter(d =>
  heatRegions.includes(d.Region) && heatWinners.includes(d.Winner24)
)
function pearson(data, v1, v2) {
  const pairs = data.map(d => [+d[v1], +d[v2]]).filter(([x,y]) => isFinite(x) && isFinite(y));
  if (pairs.length < 2) return 0;
  const xs = pairs.map(p=>p[0]), ys = pairs.map(p=>p[1]);
  const mx = d3.mean(xs), my = d3.mean(ys);
  const num = d3.sum(pairs.map(([x,y]) => (x-mx)*(y-my)));
  const den = Math.sqrt(d3.sum(xs.map(x=>(x-mx)**2)) * d3.sum(ys.map(y=>(y-my)**2)));
  return den === 0 ? 0 : num/den;
}
corrData = {
  const vars = heatVars.length >= 2 ? heatVars : defaultHeatVars.slice(0,5);
  const result = [];
  for (const v1 of vars) for (const v2 of vars)
    result.push({v1: allVarLabels[v1]||v1, v2: allVarLabels[v2]||v2, r: pearson(filteredHeat,v1,v2)});
  return result;
}
heatPlot = Plot.plot({
  marks: [
    Plot.cell(corrData, {x:"v2", y:"v1", fill:"r", tip:true}),
    Plot.text(corrData, {x:"v2", y:"v1", text: d=>d.r.toFixed(2), fill: d=>Math.abs(d.r)>0.45?"white":"#333", fontSize:9})
  ],
  color: {type:"diverging", scheme:"RdBu", reverse:true, domain:[-1,1], legend:true},
  x: {tickRotate:-40, label:null}, y: {label:null},
  marginBottom:120, marginLeft:160, width:850, height:700
})