# Display matplotlib figures inline in this Jupyter notebook.
%matplotlib inline
# Standard library imports for path setup and warning control.
import warnings # silence noisy third-party warnings during demos
from pathlib import Path # filesystem paths for locating sample data
# Third-party GIS / plotting / tabular stack used throughout the notebook.
import geopandas as gpd # GeoDataFrame I/O for tracts and counties
import matplotlib.pyplot as plt # figure and axes creation for maps
import numpy as np # array ops for shares, norms, and masks
import pandas as pd # tabular display of composition and indices
from IPython.display import display # rich table previews in the notebook
# Hide library warnings so the notebook output stays readable.
warnings.filterwarnings("ignore") # run this analysis or plotting step
# ===================================================================
# Setup for Buffalo metro segregation demos.
# Import GeoLattice, point DATA at Data/03_spatial_analysis/data_segregation/buffalo,
# import segregation as seg, load the tract panel, and define map helpers.
# ===================================================================
# The installed package lives in src/; the repository root is its parent.
import geolattice
ROOT = Path(geolattice.__file__).resolve().parents[1]
if not (ROOT / "Data").is_dir():
raise FileNotFoundError("Could not find the GeoLattice repository root.")
# Buffalo metro sample data (Erie + Niagara tracts on a shared 2020 geography).
DATA = ROOT / "Data" / "03_spatial_analysis" / "data_segregation" / "buffalo" # define DATA
# Segregation indices, local measures, profiles, and inference helpers.
from geolattice.spatial_analysis import segregation as seg
# Compact figures with top/right spines removed for a cleaner look.
plt.rcParams.update( # run this analysis or plotting step
{"figure.dpi": 110, "axes.spines.top": False, "axes.spines.right": False}
)
GROUPS = ["white", "black", "hispanic", "asian"] # main race/ethnicity count columns
ALL_GROUPS = GROUPS + ["other"] # include residual other category in totals
YEARS = (2000, 2010, 2020) # panel years available in the sample
# Panel on the 2020 tract geometry (2000 and 2010 interpolated onto it).
tracts = { # define tracts
2000: gpd.read_file(DATA / "tracts_2000_on2020.geojson"), # 2000 counts on 2020 boundaries
2010: gpd.read_file(DATA / "tracts_2010_on2020.geojson"), # 2010 counts on 2020 boundaries
2020: gpd.read_file(DATA / "tracts_2020.geojson"), # native 2020 tracts
}
counties = gpd.read_file(DATA / "counties.geojson") # Erie and Niagara outlines
CORE = (662_000, 4_738_000, 692_000, 4_768_000) # 30 km window on the City of Buffalo (UTM 17N, m)
CITY_HALL = (673_249, 4_750_383) # City Hall marker for the core window
def add_context(ax, core=False, labels=True):
"""Draw county boundaries and optionally zoom to the City of Buffalo window."""
counties.boundary.plot(ax=ax, color="0.25", lw=0.8) # county outlines for context
if core: # apply the city-window zoom when requested
ax.set_xlim(CORE[0], CORE[2]) # zoom to city window
ax.set_ylim(CORE[1], CORE[3]) # run this analysis or plotting step
ax.plot(*CITY_HALL, marker="*", color="k", ms=9, mec="white") # City Hall star
elif labels:
for name, (x, y) in { # iterate over the collection
"Niagara Co.": (690_000, 4_790_000), # run this analysis or plotting step
"Erie Co.": (700_000, 4_715_000), # run this analysis or plotting step
}.items(): # run this analysis or plotting step
ax.text(x, y, name, fontsize=8, color="0.25", ha="center") # run this analysis or plotting step
ax.set_axis_off() # hide coordinate ticks on maps
return ax # return the computed result
def metro_and_core(
gdf, values, title="", cmap="RdBu_r", norm=None, vmin=None, vmax=None,
label="", significant=None, axes=None, # define label
):
"""Side-by-side metro-wide and city-window choropleths of the same values."""
if axes is None: # create defaults when the caller omitted them
fig, axes = plt.subplots( # run this analysis or plotting step
1, 2, figsize=(13, 6.2), # run this analysis or plotting step
gridspec_kw={"width_ratios": [1, 1.25]}, # define gridspec_kw
constrained_layout=True, # define constrained_layout
)
else:
fig = axes[0].figure # figure handle
g = gdf.assign(_v=np.asarray(values, dtype=float)) # attach plot column
kw = dict( # extra keyword arguments for compute()
column="_v", cmap=cmap, norm=norm, # define column
vmin=None if norm else vmin, vmax=None if norm else vmax, # define vmin
edgecolor="white", linewidth=0.2, # define edgecolor
)
for ax, core in zip(axes, (False, True)): # iterate paired sequences together
g.plot(ax=ax, **kw) # draw geometries or a series on the axes
if significant is not None: # hatch tracts that fail significance
# Hatch tracts that are not statistically significant.
g[~np.asarray(significant)].plot( # draw geometries or a series on the axes
ax=ax, facecolor="none", edgecolor="0.3", hatch="////", linewidth=0.2 # axes handle for drawing
)
add_context(ax, core=core) # run this analysis or plotting step
axes[0].set_title(f"{title}\nBuffalo metro (Erie + Niagara)", fontsize=10) # set labels, title, or axis limits
axes[1].set_title("City of Buffalo and inner suburbs (star = City Hall)", fontsize=10) # set labels, title, or axis limits
sm = plt.cm.ScalarMappable( # mappable used to draw the colour bar
cmap=cmap, # define cmap
norm=norm or plt.Normalize( # matplotlib colour normalisation
vmin if vmin is not None else np.nanmin(values), # run this analysis or plotting step
vmax if vmax is not None else np.nanmax(values), # run this analysis or plotting step
),
)
fig.colorbar(sm, ax=list(axes), shrink=0.75, label=label) # attach a colour bar to the figure
return axes # return the computed result
print("repo:", ROOT) # run this analysis or plotting step
print("data:", DATA) # run this analysis or plotting step
print("geopandas", gpd.__version__, "| CRS", tracts[2020].crs) # run this analysis or plotting step
print({y: f"{len(g)} tracts, {g.total.sum():,.0f} people" for y, g in tracts.items()}) # run this analysis or plotting step