brycewang-stanford/Auto-Empirical-Research-Skills / skills/22-christopherkenny-skills/skills/redistricting-analysis
redistricting-analysis
VerifiedRedistricting analysis in R using the redistverse ecosystem. Use whenever the user is working with redist, redistmetrics, ggredist, geomander, adj, alarmdata, PL94171, censable, easycensus, tinytiger, baf, rict, or redistio. Covers the complete pipeline: Census and spatial data loading, adjacency graph construction, SMC/MCMC simulation, constraints (population balance, county splits, VRA compliance), convergence diagnostics, plan metrics (compactness, partisan fairness, splits), visualization, summary tables, and interactive plan drawing. Invoke whenever the user mentions redistricting, gerrymandering, district plans, simulation ensembles, or any redistverse package by name.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 5.8 KB |
| references/01-redist-simulation.md | markdown | 5.7 KB |
| references/02-redist-constraints.md | markdown | 5.0 KB |
| references/03-redist-advanced.md | markdown | 3.2 KB |
| references/04-redistmetrics-compactness.md | markdown | 4.1 KB |
| references/05-redistmetrics-partisan.md | markdown | 4.6 KB |
| references/06-redistmetrics-other.md | markdown | 4.5 KB |
| references/07-ggredist.md | markdown | 4.6 KB |
| references/08-adj.md | markdown | 4.2 KB |
| references/09-geomander-adjacency.md | markdown | 6.1 KB |
| references/10-geomander-spatial.md | markdown | 6.7 KB |
| references/11-geomander-data.md | markdown | 4.3 KB |
| references/12-alarmdata.md | markdown | 4.2 KB |
| references/13-pl94171.md | markdown | 3.6 KB |
| references/14-census-utilities.md | markdown | 5.2 KB |
| references/15-baf.md | markdown | 3.4 KB |
| references/16-rict.md | markdown | 3.4 KB |
| references/17-redistio.md | markdown | 4.3 KB |
references/07-ggredist.md
View on GitHub# ggredist — Visualization
## Overview
`ggredist` extends `ggplot2` with geoms, scales, and themes designed specifically for redistricting maps and election data. The key innovation is `geom_district()`, which dissolves precinct polygons into district regions and handles adjacent-district coloring automatically.
## Core Geom: `geom_district()`
Dissolves precinct-level `sf` geometries into district polygons and fills them by a variable. The `group` aesthetic specifies the district assignment column.
```r
library(ggredist)
library(ggplot2)
# Basic district map — color by district number
ggplot(map, aes(fill = cd_2020, group = cd_2020)) +
geom_district() +
theme_map()
# Partisan vote share (fill + denom computes the ratio automatically)
ggplot(map, aes(fill = ndv, group = cd_2020, denom = ndv + nrv)) +
geom_district() +
scale_fill_party_c() +
theme_map()
```
### Key Aesthetics
| Aesthetic | Description |
|-----------|-------------|
| `group` | District assignment column (required) |
| `fill` | Numerator for fill; if `denom` is provided, computes `fill/denom` |
| `denom` | Denominator for ratio fill (optional) |
| `color` | Border color (default: black) |
| `linewidth` | Border width (default: 0.3) |
### Auto-coloring Adjacent Districts
`ggredist` uses `adj_color()` from the `adj` package to automatically assign colors so adjacent districts differ. Pass `color_adj = TRUE` (or use the `adj` from the map):
```r
ggplot(map, aes(group = cd_2020)) +
geom_district(aes(fill = adj_color(map))) +
scale_fill_distiller() +
theme_map()
```
## District Labels
Add district numbers or names at district centroids:
```r
ggplot(map, aes(fill = ndv / (ndv + nrv), group = cd_2020,
denom = ndv + nrv)) +
geom_district() +
geom_district_text(aes(label = cd_2020), size = 3, color = 'white') +
scale_fill_party_c() +
theme_map()
```
## Place Labels
Overlay Census-designated places (cities, towns) for geographic context:
```r
ggplot(map, aes(fill = cd_2020, group = cd_2020)) +
geom_district() +
geom_places(state = 'MD', size = 2) + # 'MD' or FIPS code
theme_map()
```
## Color Scales
### Partisan Scales
```r
scale_fill_party_c(midpoint = 0.5, limits = c(0, 1)) # continuous red-white-blue
scale_fill_party_b(breaks = c(0.4, 0.5, 0.6)) # binned version
scale_color_party_c() # for color= aesthetic
```
The midpoint (default 0.5) maps to white; values above are blue (Democratic), below are red (Republican).
### Cartographic Palettes
Discrete palettes for coloring districts by number:
```r
scale_fill_penn82() # Penn82 atlas palette
scale_fill_natgeo() # National Geographic style
scale_fill_randmcnally() # Rand McNally atlas palette
scale_fill_fivethirtyeight() # FiveThirtyEight electoral palette
scale_fill_wiki() # Wikipedia map palette
```
## Clean Map Theme
```r
theme_map() # removes axes, gridlines, background; keeps legend
```
Combine with `coord_sf(datum = NA)` to suppress the lat/lon grid:
```r
ggplot(map, aes(fill = cd_2020, group = cd_2020)) +
geom_district() +
scale_fill_penn82() +
theme_map() +
coord_sf(datum = NA)
```
## Visualizing the Ensemble
### Distribution Plots
Use base `redist` functions to plot metric distributions:
```r
# Histogram of efficiency gap with enacted plan highlighted
hist(plans, part_egap(pl(), ndv, nrv))
# Box/jitter plot of district-level Polsby-Popper
plot(plans, comp_polsby(pl(), map, perim_df), style = 'box')
# Scatter plot of two metrics across plans
plot(plans, x = part_egap(pl(), ndv, nrv),
y = splits_admin(pl(), map, map$county))
```
### Mapping a Specific Plan
```r
# Extract one plan's assignments into the map sf
one_plan <- get_plans_matrix(plans)[, 1] # plan 1, 0-indexed
map$district <- one_plan + 1 # 1-indexed
ggplot(map, aes(fill = ndv / (ndv + nrv), group = district,
denom = ndv + nrv)) +
geom_district() +
scale_fill_party_c() +
theme_map()
```
### Grid of Plans
```r
library(patchwork)
# Map multiple plans side by side
plot_plan <- function(k) {
map$district <- get_plans_matrix(plans)[, k] + 1
ggplot(map, aes(fill = district, group = district)) +
geom_district() +
scale_fill_penn82() +
theme_map() +
labs(title = paste('Plan', k))
}
plot_plan(1) + plot_plan(2) + plot_plan(3) + plot_plan(4)
```
## See Also
- Adjacency graph coloring: [08-adj.md](08-adj.md) (`adj_color()`)
- Simulation output (`redist_plans`): [01-redist-simulation.md](01-redist-simulation.md)
- Partisan metrics for fill values: [05-redistmetrics-partisan.md](05-redistmetrics-partisan.md)
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deployment | Stars: 323k | Updated | Claude CodeCodex | Verified | Install |
| xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy. | Stars: 119k | Updated | Claude CodeCodex | Verified | Install |
| childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |