Repository navigation
Expand file tree
/
Copy pathus_population_simple.py
More file actions
67 lines (56 loc) · 2.25 KB
/
Copy pathus_population_simple.py
File metadata and controls
67 lines (56 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""2020 Census resident population by state, with a ColorBrewer palette.
Downloads public population counts and state boundaries on first run; no API
key or manually prepared GeoJSON is needed. See README.md for data sources.
"""
import geopandas as gpd
import matplotlib.pyplot as plt
import pandas as pd
from chorokit import plot_us_choropleth, LegendConfig, LayoutConfig
from _common import OUT, RAW, fetch, state_geometries
POPULATION_URL = (
"https://www2.census.gov/programs-surveys/decennial/2020/"
"data/apportionment/apportionment.csv"
)
def load_population() -> gpd.GeoDataFrame:
path = fetch(POPULATION_URL, RAW / "census_apportionment_1910_2020.csv")
table = pd.read_csv(path, thousands=",")
# Use residents, not apportionment population (which includes some people
# living overseas). The source contains many decades and national totals.
population = table.loc[table["Year"].eq(2020), ["Name", "Resident Population"]]
states = state_geometries()
joined = states.merge(
population, left_on="name", right_on="Name", how="left", validate="one_to_one",
)
if joined["Resident Population"].isna().any():
missing = joined.loc[joined["Resident Population"].isna(), "name"].tolist()
raise ValueError(f"Missing 2020 Census counts for: {missing}")
joined["pop_millions"] = joined["Resident Population"] / 1_000_000
return joined
def main() -> None:
gdf = load_population()
legend = LegendConfig(
kind="binned",
palette=("Greens", 7),
scheme="natural",
round_breaks=True,
label_style="boundary",
title="Population (millions)",
location="top",
)
layout = LayoutConfig(
title="2020 U.S. state population",
subtitle="50 states and D.C., April 1, 2020; Alaska and Hawaii repositioned",
source="Source: U.S. Census Bureau, 2020 Census",
width=12.0,
)
fig, _ = plot_us_choropleth(
gdf, value="pop_millions", legend=legend, layout=layout,
edgecolor="#b8c4b8", linewidth=0.3,
)
OUT.mkdir(parents=True, exist_ok=True)
output = OUT / "us_population_simple.png"
fig.savefig(output, dpi=300)
plt.close(fig)
print(f"wrote {output}")
if __name__ == "__main__":
main()