from pathlib import Path from hashlib import sha256 import json, math, csv import requests import pandas as pd import numpy as np from PIL import Image, ImageOps import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt HERE=Path(__file__).resolve().parent ROOT=next((p for p in HERE.parents if (p/"config/launch-sites.json").is_file()),None) SOURCE="https://data.census.gov/table/ACSDT5Y2024.B25074" PHOTO="https://upload.wikimedia.org/wikipedia/commons/5/54/Alma_Apartments%2C_Friendship%2C_2026-08-25-2.jpg" AREAS={"0100000US":"United States","0500000US42003":"Allegheny","0500000US39035":"Cuyahoga", "0500000US39061":"Hamilton","0500000US26163":"Wayne","0500000US55079":"Milwaukee"} INC=["Under $10k","$10k–19.9k","$20k–34.9k","$35k–49.9k","$50k–74.9k","$75k–99.9k","$100k and up"] plans=[]; sources=[]; rows=[] for year in (2019,2024): name=f"acsdt5y{year}-b25074.dat" url=f"https://www2.census.gov/programs-surveys/acs/summary_file/{year}/table-based-SF/data/5YRData/{name}" path=ROOT/f"data/bulk/acs_5yr/{year}/{name}" if ROOT else HERE/name if not path.exists(): path=HERE/name with requests.get(url,stream=True,timeout=120) as response,path.open("wb") as out: response.raise_for_status() for block in response.iter_content(chunk_size=1024*1024): out.write(block) with path.open("rb") as inp: import hashlib digest=hashlib.file_digest(inp,"sha256").hexdigest() sources.append({"url":url,"sha256":digest,"year":year}) with path.open(encoding="utf-8-sig",newline="") as handle: for row in csv.DictReader(handle,delimiter="|"): geoid=row["GEO_ID"] if geoid not in AREAS: continue for i, band in enumerate(INC): start=2+i*9 estimates=[int(row[f'B25074_E{start+j:03}']) for j in range(9)] errors=[int(row[f'B25074_M{start+j:03}']) for j in range(9)] assert min(estimates+errors)>=0 and sum(estimates[1:])==estimates[0] rows.append([year,AREAS[geoid],band,*estimates[1:],*errors[1:]]) fields=["Below 20","20–24.9","25–29.9","30–34.9","35–39.9","40–49.9","50 and up","Not computed"] d=pd.DataFrame(rows,columns=["Vintage","Place","Income bracket",*fields,*[f"{x} MOE" for x in fields]]) assert len(d)==84 d["Known"]=d[fields[:7]].sum(axis=1);d["Burdened"]=d[fields[3:7]].sum(axis=1) d["Severe"]=d["50 and up"];d["Moderate"]=d["Burdened"]-d["Severe"] for label,cols in (("Known",fields[:7]),("Burdened",fields[3:7]),("Severe",fields[6:7])): d[label+" MOE"]=np.sqrt(sum(d[c+" MOE"]**2 for c in cols)) for label in ("Burdened","Severe"): ratio=d[label]/d.Known d[label+" %"]=100*ratio subtract=d[label+" MOE"]**2-ratio**2*d["Known MOE"]**2 add=d[label+" MOE"]**2+ratio**2*d["Known MOE"]**2 d[label+" share MOE (pp)"]=100*np.sqrt(np.where(subtract>=0,subtract,add))/d.Known d.to_csv(HERE/"income-and-rent-matrix.csv",index=False) regions=list(AREAS.values()) ag=d.groupby(["Vintage","Place"],sort=False)[["Known","Burdened","Moderate","Severe","Not computed"]].sum() ag["Rate"]=100*ag["Burdened"]/ag["Known"] ag["Missing all below"]=100*ag.Burdened/(ag.Known+ag["Not computed"]) ag["Missing all above"]=100*(ag.Burdened+ag["Not computed"])/(ag.Known+ag["Not computed"]) ag["Moderate %"]=100*ag["Moderate"]/ag.Known;ag["Severe %"]=100*ag["Severe"]/ag.Known ag.to_csv(HERE/"county-and-national-totals.csv") pre=d[d.Vintage.eq(2019)].set_index(["Place","Income bracket"]) post=d[d.Vintage.eq(2024)].set_index(["Place","Income bracket"]) w0=pre.Known/pre.Known.groupby(level=0).transform("sum") w1=post.Known/post.Known.groupby(level=0).transform("sum") decomp=pd.DataFrame({"Earlier mix (%)":w0*100,"Later mix (%)":w1*100, "Composition contribution (pp)":(w1-w0)*pre["Burdened %"], "Within-band contribution (pp)":w1*(post["Burdened %"]-pre["Burdened %"])}) decomp.to_csv(HERE/"mix-accounting.csv") paper="#faf0e7"; ink="#34262b"; rust="#9e463c"; slate="#385574"; teal="#2a6e5f"; gold="#a67128"; pale="#b7a4a0" plt.rcParams.update({"figure.facecolor":paper,"axes.facecolor":paper,"axes.labelcolor":ink,"xtick.color":ink, "ytick.color":ink,"font.family":"DejaVu Sans","font.size":12,"axes.axisbelow":True, "axes.spines.top":False,"axes.spines.right":False,"axes.spines.left":False,"axes.spines.bottom":False}) def chart(name,title,question,unit,takeaway,table,period="2015–2019 and 2020–2024 ACS"): (HERE/"charts").mkdir(exist_ok=True) dest=f"charts/chart-{len(plans)+1:02d}-{name}" table.to_csv(HERE/(dest+".csv"),index=True,float_format="%.5f") plans.append({"asset":dest+".png","data":dest+".csv","title":title,"question":question, "source":SOURCE,"population":"Renter-occupied housing units in the relevant ACS detailed table", "period":period,"unit":unit,"takeaway":takeaway}) fig,ax=plt.subplots(figsize=(11.4,6.0),dpi=160) fig.subplots_adjust(top=.76,bottom=.19,left=.188,right=.94) fig.text(.075,.925,"RENT & ROOF / THE RENTAL LEDGER",fontsize=11,color=rust,weight="bold") fig.text(.075,.844,title,fontsize=21,color=ink,weight="bold") fig.text(.075,.062,"U.S. Census Bureau, ACS B25074 • Rent & Roof calculations • "+period,fontsize=10,color=ink) ax.grid(axis="x",alpha=.27,linewidth=.85);ax.tick_params(length=0,pad=8,labelsize=11) return fig,ax,HERE/(dest+".png") def end(f,p): f.savefig(p,dpi=160) plt.close(f) def legend(a,loc): a.legend(loc=loc,labelcolor=ink,frameon=True,facecolor=paper,edgecolor=pale) def labels(a,names): a.set_yticks(range(len(names)),names) a.invert_yaxis() def pair(a, x, y, first, second): for j, (lo,hi) in enumerate(zip(x,y,strict=True)): a.plot([lo,hi],[j,j],color=pale,linewidth=2) a.scatter(x,range(len(x)),color=slate,label=first,s=53,zorder=4) a.scatter(y,range(len(y)),color=rust,label=second,s=53,zorder=4) local=post.loc["Cuyahoga"][["Burdened %"]].join(pre.loc["Cuyahoga"][["Burdened %"]],rsuffix=" earlier") f,a,p=chart("cuyahoga-rates","A flat county rate hides steep jumps","Where did renter burden rise within reported income brackets in Cuyahoga?", "Percent of renter units with computable ratio","The rise was most visible in the middle-income bands.",local) pair(a,local.iloc[:,1],local.iloc[:,0],"2015–2019","2020–2024");labels(a,INC);a.set(xlim=(0,104),xlabel="Share paying at least 30% of income (%)");legend(a,"lower right");end(f,p) mix=decomp[["Composition contribution (pp)","Within-band contribution (pp)"]].groupby(level=0).sum().reindex(regions) mix["Combined (pp)"]=mix.sum(axis=1) f,a,p=chart("opposing-movements","The two contributions offset each other","How much of each overall difference is associated with income composition and within-band rates?", "Percentage point contributions","Both pieces are much larger than the net difference.",mix) y=np.arange(len(regions));a.barh(y,mix.iloc[:,0],color=slate,height=.5,label="Income composition") a.barh(y,mix.iloc[:,1],color=rust,height=.5,label="Within-band rates") a.axvline(0,color=ink,linewidth=1);a.scatter(mix.iloc[:,2],y,color=ink,s=33,zorder=5,label="Net change") labels(a,regions);a.set(xlim=(-13,14),xlabel="Contribution to change (percentage points)");a.legend(loc="lower left",bbox_to_anchor=(0,1.01),ncol=3,frameon=False,labelcolor=ink);end(f,p) values=pd.DataFrame({"Allegheny 2015–19":decomp.loc["Allegheny","Earlier mix (%)"],"Allegheny 2020–24":decomp.loc["Allegheny","Later mix (%)"], "Cuyahoga 2015–19":decomp.loc["Cuyahoga","Earlier mix (%)"],"Cuyahoga 2020–24":decomp.loc["Cuyahoga","Later mix (%)"]}) f,a,p=chart("income-mix","The later renter mix leans higher","Which renter-income brackets became more or less common in the two counties?", "Percent of units with computable ratio","Both counties gained share at $75,000 and above.",values) for i,(name,color) in enumerate(zip(values.columns,[slate,rust,teal,gold],strict=True)): a.barh(np.arange(7)+(i-1.5)*.2,values[name],height=.18,label=name,color=color) labels(a,INC);a.set_xlabel("Share of computable renter estimates (%)");a.legend(loc="lower left",bbox_to_anchor=(0,1.01),ncol=4,frameon=False,labelcolor=ink,fontsize=9.5);end(f,p) delta=(post.loc["Cuyahoga",["Known","Burdened"]]-pre.loc["Cuyahoga",["Known","Burdened"]]) f,a,p=chart("cuyahoga-counts","The middle adds burdened renters","Which brackets supplied the change in Cuyahoga’s total number of burdened renter units?", "Change in estimated renter units","Increases in middle bands offset losses in lower ones.",delta) a.barh(np.arange(7)-.17,delta.Known,height=.30,color=slate,label="All computable"); a.barh(np.arange(7)+.17,delta.Burdened,height=.30,color=rust,label="Paying 30% or more") labels(a,INC);a.axvline(0,color=ink,linewidth=.9);a.set_xlabel("Change in estimated renter units");legend(a,"lower right");end(f,p) a0=pre.loc["United States",["Severe %","Severe share MOE (pp)"]].add_suffix(" earlier") a1=post.loc["United States",["Severe %","Severe share MOE (pp)"]].add_suffix(" later") values=a0.join(a1) f,a,p=chart("us-severe","Severe burden rose in key income bands","How did the share paying half or more change nationally within income bands?", "Percent, approximate 90% margins","The increases are most visible between $20,000 and $49,999.",values) for offset,colour,part,name in [(-.13,slate," earlier","2015–2019"),(.13,rust," later","2020–2024")]: a.errorbar(values["Severe %"+part],np.arange(7)+offset,xerr=values["Severe share MOE (pp)"+part],fmt="o",color=colour,label=name,capsize=3) labels(a,INC);a.set(xlim=(0,103),xlabel="Share paying at least half of income (%)");legend(a,"lower right");end(f,p) v=ag.loc[2024,["Moderate %","Severe %"]].reindex(regions) f,a,p=chart("recent-severity","The county burden includes two levels","How is the later overall burden split across moderate and severe ratios?", "Percent of units with computable ratio","The share paying half or more is substantial in every selected county.",v,period="2020–2024 ACS") a.barh(regions,v.iloc[:,0],color=gold,label="30% to 49.9%") a.barh(regions,v.iloc[:,1],left=v.iloc[:,0],color=rust,label="At least 50%") a.invert_yaxis();a.set(xlim=(0,66),xlabel="Share of renter units with computable ratio (%)");legend(a,"lower right");end(f,p) b="\\$35k" bands=INC[3:5] measures=post.loc[([*regions],bands),["Burdened %","Burdened share MOE (pp)"]] earlier=pre.loc[([*regions],bands),["Burdened %","Burdened share MOE (pp)"]] ch=(measures["Burdened %"]-earlier["Burdened %"]).to_frame("Change (pp)") ch["Approximate 90% margin (pp)"]=np.hypot(measures["Burdened share MOE (pp)"],earlier["Burdened share MOE (pp)"]) f,a,p=chart("two-band-changes","The middle-band changes recur","Did the two middle-income burden changes exceed approximate sampling margins?", "Percentage points, approximate 90% margins","The positive differences recur across the national estimate and selected counties.",ch) for off,color,band in [(-.16,rust,bands[0]),(.16,slate,bands[1])]: x=ch.xs(band,level="Income bracket").reindex(regions) a.errorbar(x.iloc[:,0],np.arange(len(regions))+off,xerr=x.iloc[:,1],fmt="o",color=color,capsize=3,label=band) labels(a,regions);a.set(xlim=(0,34),xlabel="Change in burden rate (percentage points)");legend(a,"lower right");end(f,p) v=ag.loc[2024,["Missing all below","Rate","Missing all above","Not computed"]].reindex(regions) f,a,p=chart("unmeasured", "The uncomputed group sets a boundary","How far can the share move under the extremes for uncomputed ratios?", "Percent of all units at the bounds, computable units for dots","The endpoints describe missingness extremes, not confidence limits.",v,period="2020–2024 ACS") for i,(_,row) in enumerate(v.iterrows()): a.plot([row.iloc[0],row.iloc[2]],[i,i],color=slate,linewidth=4,alpha=.8) a.scatter(row.Rate,i,color=rust,s=68,zorder=4) labels(a,regions);a.set(xlim=(39,64),xlabel="Share paying at least 30% of income (%)");end(f,p) asset=HERE/"alma.jpg" if not asset.exists(): r=requests.get(PHOTO,headers={"User-Agent":"Rent and Roof editorial research (support@rentandroof.com)"},timeout=30) r.raise_for_status() asset.write_bytes(r.content) with Image.open(asset) as im: img=ImageOps.contain(ImageOps.exif_transpose(im).convert("RGB"),(1540,1540),Image.Resampling.LANCZOS) img.save(HERE/"hero.webp",quality=86,method=6) meta={"title":"Alma Apartments in Pittsburgh’s Friendship neighborhood", "alt":"Railings and stacked balconies frame a pair of arched doors on the brick Alma Apartments facade.", "caption":"The Alma Apartments in Pittsburgh’s Friendship neighborhood in August 2026. The building illustrates a local rental setting. The survey estimates are countywide.", "credit":"Father Pitt / Cbaile19 via Wikimedia Commons","source_url":"https://commons.wikimedia.org/wiki/File:Alma_Apartments,_Friendship,_2026-08-25-2.jpg", "license":"CC0 1.0","license_url":"https://creativecommons.org/publicdomain/zero/1.0/","original_url":PHOTO, "original_sha256":sha256(asset.read_bytes()).hexdigest(),"processing":"Resized without cropping or upscaling and encoded as WebP."} for filename,obj in [("CHART-PLAN.json",plans),("HERO.json",meta),("source-manifest.json",sources)]: (HERE/filename).write_text(json.dumps(obj,ensure_ascii=False,indent=2)+"\n",encoding="utf-8") print(mix.round(2).to_string()) print(ch.round(2).to_string()) print(v.round(2).to_string())