"""Reproduce Rent & Roof's owner-cost exhibits from Census B25091 source cells.""" from pathlib import Path import json import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.ticker import PercentFormatter import numpy as np import pandas as pd HERE = Path(__file__).resolve().parent OUT = HERE/"charts" OUT.mkdir(exist_ok=True) PAPER = "#fbf2e7" INK = "#35232b" MORT = "#793c53" FREE = "#15675e" DIM = "#715e65" PERIODS = {2018: "2014–18", 2024: "2020–24"} US = "0100000US" FIPS = ("01 AL 02 AK 04 AZ 05 AR 06 CA 08 CO 09 CT 10 DE 11 DC 12 FL 13 GA 15 HI 16 ID " "17 IL 18 IN 19 IA 20 KS 21 KY 22 LA 23 ME 24 MD 25 MA 26 MI 27 MN 28 MS 29 MO 30 MT " "31 NE 32 NV 33 NH 34 NJ 35 NM 36 NY 37 NC 38 ND 39 OH 40 OK 41 OR 42 PA 44 RI 45 SC " "46 SD 47 TN 48 TX 49 UT 50 VT 51 VA 53 WA 54 WV 55 WI 56 WY").split() STATE = dict(zip(FIPS[::2],FIPS[1::2])) REGIONS = {s:r for r,codes in { "Northeast":"CT ME MA NH RI VT NJ NY PA", "Midwest":"IN IL MI OH WI IA KS MN MO NE ND SD", "South":"DE DC FL GA MD NC SC VA WV AL KY MS TN AR LA OK TX", "West":"AZ CO ID MT NV NM UT WY AK CA HI OR WA" }.items() for s in codes.split()} SOURCE=["https://data.census.gov/table/ACSDT5Y2018.B25091", "https://data.census.gov/table/ACSDT5Y2024.B25091"] STYLE={"font.family":"DejaVu Sans","font.size":12,"axes.labelcolor":INK,"text.color":INK, "axes.edgecolor":"#c2a9a7","xtick.color":DIM,"ytick.color":DIM, "figure.facecolor":PAPER,"axes.facecolor":PAPER,"axes.spines.top":False, "axes.spines.right":False,"figure.dpi":150} rows=pd.read_csv(HERE/"source-cells.csv").set_index(["vintage","geoid"]).sort_index() nums=lambda n: f"estimate_{n:03}" def group(data,status): offset=0 if status=="With mortgage" else 11 count=lambda low,high: data[[nums(n+offset) for n in range(low,high+1)]].sum(axis=1) usable=data[nums(2+offset)]-data[nums(12+offset)] assert usable.eq(count(3,11)).all() return pd.DataFrame({"owners":data[nums(2+offset)],"usable":usable, "burdened":count(8,11),"severe":data[nums(11+offset)], "ratio_unknown":data[nums(12+offset)]}) by={} for status in ("With mortgage","Without mortgage"): by[status]=group(rows,status).assign(status=status) states = pd.concat(by.values()).reset_index() states["place"]=states.geoid.map(lambda x:"US" if x==US else STATE[x[-2:]]) states["burden_pct"]=100*states.burdened/states.usable states["severe_pct"]=100*states.severe/states.usable states["region"]=states.place.map(REGIONS).fillna("U.S.") states.to_csv(HERE/"state-status.csv", index=False) nat=states[states.place=="US"].copy() geo=states[states.place!="US"].copy() regional=geo.groupby(["vintage","region","status"],as_index=False)[["owners","usable","burdened","severe"]].sum() regional["rate"]=100*regional.burdened/regional.usable reg2024=regional[regional.vintage==2024].pivot(index="region",columns="status",values="rate") wide=geo.pivot(index=["vintage","place"],columns="status",values=["owners","usable","burdened","severe","burden_pct","severe_pct"]) current=wide.loc[2024] prior=wide.loc[2018] portfolio=[] def render(number,slug,data,title,question,ylabel="",xlabel=""): filename=f"chart-{number:02}-{slug}" fig,ax=plt.subplots(figsize=(9.0,5.5)) fig.subplots_adjust(left=.13,right=.96,bottom=.18,top=.80) fig.text(.055,.94,"RENT & ROOF / OWNER COSTS",fontsize=10,weight="bold",color=MORT) fig.text(.055,.87,title,fontsize=17,weight="bold",fontfamily="DejaVu Serif") fig.text(.055,.049,"Source: Census ACS five-year estimates, table B25091 · Rent & Roof analysis",fontsize=9,color=DIM) ax.set(xlabel=xlabel,ylabel=ylabel) ax.set_axisbelow(True) ax.grid(axis="y",alpha=.25,color="#a9868c") data.to_csv(OUT/(filename+".csv"),index=True) populations = [ "U.S. owner households by mortgage status", "U.S. owner households by mortgage status", "U.S. owner households by mortgage status with a computable ratio", "50 states and the District of Columbia", "Owner households in four Census regions", "50 states and the District of Columbia", "Burdened owners in 50 states and D.C.", "U.S. owner households with a computable ratio", "Selected states", "Selected states and D.C." ] units = ["Percent", "Millions of households", "Percent", "Percent", "Percent", "Percentage points", "Percent", "Percent", "Thousands of households", "Percentage points"] takeaways = [ "The rate rose among owners without mortgages and fell among those with mortgages.", "The national count of burdened owners rose in both mortgage groups.", "A larger proportion of owners without mortgages fell below 10% of income.", "Owners without mortgages are a large share of burdened owners in some states.", "The gap across the two rates was widest in the West and narrowest in the Midwest.", "The estimates rose in both groups in only 17 of the 51 jurisdictions.", "This higher threshold describes the composition of the group already reaching 30%.", "The later mortgage composition lowered the combined rate relative to a fixed mix.", "The number of affected owners grew in both groups in Florida and Texas.", "The rate gap varied widely between the selected jurisdictions." ] portfolio.append({"asset":f"charts/{filename}.png","data":f"charts/{filename}.csv", "title":title,"question":question,"source":SOURCE, "population":populations[number-1], "unit":units[number-1], "period":"2020–24 ACS" if number in {3,4,5,7,10} else "2014–18 and 2020–24 ACS", "takeaway":takeaways[number-1]}) return fig,ax,OUT/(filename+".png") def finish(fig,path): fig.savefig(path) plt.close(fig) with plt.rc_context(STYLE): why=nat.pivot(index="vintage",columns="status",values="burden_pct").rename(index=PERIODS) fig,ax,path=render(1,"burden-rate",why,"A wider share of owners without mortgages reached 30%", "How did the share with costs at least 30% of income change within each group?") why.plot.bar(ax=ax,color=[MORT,FREE],width=.62,rot=0) ax.yaxis.set_major_formatter(PercentFormatter()) ax.set_ylim(0,38) ax.set_xlabel("") ax.legend(loc="upper right",frameon=False) finish(fig,path) how=nat.pivot(index="vintage",columns="status",values="burdened").rename(index=PERIODS)/1e6 fig,ax,path=render(2,"burdened-owners",how,"More households reached the threshold in both groups", "How many owner households recorded costs of at least 30% of income?",ylabel="Millions of households") how.plot.bar(ax=ax,stacked=True,color=[MORT,FREE],width=.58,rot=0) ax.set_ylim(0,24) ax.set_xlabel("") ax.legend(loc="upper left",frameon=False) finish(fig,path) frame=rows.loc[(2024,US)] bands=["Under 10%","10–14.9%","15–19.9%","20–24.9%","25–29.9%","30–34.9%","35–39.9%","40–49.9%","50% and up"] dist=pd.DataFrame({status:[100*frame[nums(n+off)]/sum(frame[nums(i+off)] for i in range(3,12)) for n in range(3,12)] for status,off in (("With mortgage",0),("Without mortgage",11))},index=bands) fig,ax,path=render(3,"cost-distribution",dist,"The shape of the housing budget is different", "How are owners distributed across detailed cost-to-income bands?", xlabel="Share of owners in the mortgage-status group") ax.barh(np.arange(len(dist))-.18,dist["With mortgage"],.32,color=MORT,label="With mortgage") ax.barh(np.arange(len(dist))+.18,dist["Without mortgage"],.32,color=FREE,label="Without mortgage") ax.set_yticks(np.arange(len(dist)),dist.index,fontsize=10) ax.invert_yaxis() ax.xaxis.set_major_formatter(PercentFormatter()) ax.legend(loc="lower right",frameon=False) finish(fig,path) reach=pd.DataFrame({"No-mortgage share of owners":100*current.owners["Without mortgage"]/current.owners.sum(axis=1), "No-mortgage share of burdened owners":100*current.burdened["Without mortgage"]/current.burdened.sum(axis=1)}) fig,ax,path=render(4,"status-share",reach,"Where owners without mortgages make up more of the burden", "Where do owners without mortgages account for a relatively large share of burdened owners?", ylabel="Share of burdened owners without a mortgage",xlabel="Share of all owners without a mortgage") ax.scatter(reach.iloc[:,0],reach.iloc[:,1],color=FREE,s=34,alpha=.8) for k in ("WV","MS","NY","DC","ND","HI"): ax.annotate(k,(reach.loc[k].iloc[0],reach.loc[k].iloc[1]),xytext=(4,3),textcoords="offset points",fontsize=10) ax.xaxis.set_major_formatter(PercentFormatter()) ax.yaxis.set_major_formatter(PercentFormatter()) finish(fig,path) fig,ax,path=render(5,"regional-contrast",reg2024,"The gap between mortgage groups varies by region", "How far apart are the two burden rates within each Census region?", xlabel="Share with costs of at least 30% of income") index=np.arange(len(reg2024)) ax.hlines(index,reg2024["Without mortgage"],reg2024["With mortgage"],color="#b39b9f",lw=2) ax.scatter(reg2024["With mortgage"],index,color=MORT,label="With mortgage",s=65) ax.scatter(reg2024["Without mortgage"],index,color=FREE,label="Without mortgage",s=65) ax.set_yticks(index,reg2024.index) ax.xaxis.set_major_formatter(PercentFormatter()) ax.legend(loc="lower right",frameon=False) finish(fig,path) delta=current.burden_pct-prior.burden_pct fig,ax,path=render(6,"change-by-status",delta,"Some markets moved in opposite directions by mortgage status", "Where did the burden rate rise or fall in each group between the two periods?", xlabel="Change with mortgage (percentage points)", ylabel="Change without mortgage (percentage points)") ax.axhline(0,color=DIM,lw=1) ax.axvline(0,color=DIM,lw=1) ax.scatter(delta["With mortgage"],delta["Without mortgage"],color=MORT,alpha=.74,s=39) for k in ("FL","IL","WV","NY","DC","HI","MT"): ax.annotate(k,(delta.loc[k,"With mortgage"],delta.loc[k,"Without mortgage"]),xytext=(4,5),textcoords="offset points",fontsize=10) finish(fig,path) sev=100*current.severe/current.burdened fig,ax,path=render(7,"threshold-depth",sev,"Among burdened owners, the share reaching 50% varies", "How much of each state’s burdened group crossed the higher threshold?", xlabel="Share of burdened owners with a mortgage at 50% or more", ylabel="Share without a mortgage at 50% or more") start=min(sev.min())-2 stop=max(sev.max())+2 ax.plot([start,stop],[start,stop],color="#b39b9f",ls="--") ax.scatter(sev["With mortgage"],sev["Without mortgage"],color=FREE,alpha=.8,s=39) for k in ("WV","NY","DC","FL","HI"): ax.annotate(k,(sev.loc[k,"With mortgage"],sev.loc[k,"Without mortgage"]),xytext=(3,4),textcoords="offset points",fontsize=10) ax.xaxis.set_major_formatter(PercentFormatter()) ax.yaxis.set_major_formatter(PercentFormatter()) finish(fig,path) mix=nat.pivot(index="vintage",columns="status",values=["usable","burden_pct"]) weights=mix.usable.div(mix.usable.sum(axis=1),axis=0) baseline=(weights.loc[2018]*mix.burden_pct.loc[2018]).sum() within=(weights.loc[2018]*mix.burden_pct.loc[2024]).sum() actual=(weights.loc[2024]*mix.burden_pct.loc[2024]).sum() counter=pd.Series({"2014–18 actual":baseline,"2020–24 rates,\nearlier mix":within,"2020–24 actual":actual},name="Housing costs ≥30%") fig,ax,path=render(8,"mix-counterfactual",counter,"The changing mix helped push down the overall rate", "What would the combined rate be if the mortgage-status mix had stayed at its earlier levels?") bars=ax.bar(counter.index,counter,color=[MORT,"#af676c",FREE],width=.55) ax.bar_label(bars,labels=[f"{v:.2f}%" for v in counter],padding=4) ax.yaxis.set_major_formatter(PercentFormatter()) ax.set_ylim(0,counter.max()+5) finish(fig,path) volume=(current.burdened-prior.burdened)/1000 chosen=["CA","TX","FL","NY","WV","IL","NJ","AZ","PA"] shown=volume.loc[chosen].sort_values("Without mortgage") fig,ax,path=render(9,"local-count-change",shown,"Affected owners increased in both groups in Florida and Texas", "Among selected states, how much did the number of burdened owners change in each mortgage group?", xlabel="Change in number of affected owners (thousands)") shown.plot.barh(ax=ax,color=[MORT,FREE],width=.75) ax.axvline(0,color=DIM,lw=1) ax.legend(loc="upper left",frameon=False,fontsize=10) finish(fig,path) difference=(current.burden_pct["With mortgage"]-current.burden_pct["Without mortgage"]).sort_values() picks=["DC","NY","FL","WV","CA","TX","ND","HI","WA"] example=difference.loc[picks].sort_values() fig,ax,path=render(10,"local-rate-gaps",example,"Mortgage status changes the picture by different amounts", "Which of the selected markets have the largest gap between the two burden rates?", xlabel="With-mortgage rate minus without-mortgage rate (percentage points)") ax.barh(example.index,example,color=MORT,alpha=.89) ax.set_ylim(-.5,len(example)-.45) finish(fig,path) (HERE/"CHART-PLAN.json").write_text(json.dumps(portfolio,indent=2,ensure_ascii=False)+"\n",encoding="utf8") summary={"national":nat.round(3).to_dict("records"), "regional":reg2024.round(3).to_dict("index"), "mix":{k:round(v,4) for k,v in counter.items()}, "places":geo[geo.place.isin(["WV","NY","DC","FL","CA","TX","IL","HI","MS","ND"])].round(3).to_dict("records"), "comparison":{"both_rates_up":int(((delta["With mortgage"]>0)&(delta["Without mortgage"]>0)).sum()), "without_rate_up":int((delta["Without mortgage"]>0).sum()), "with_rate_up":int((delta["With mortgage"]>0).sum()), "national_burdened_growth_by_group":nat.pivot(index="vintage",columns="status",values="burdened").diff().iloc[-1].to_dict(), "selected_owner_without_shares":reach.loc[["WV","MS","NY","DC","ND","HI"]].round(2).to_dict("index"), "selected_total_changes":shown.round(2).to_dict("index"), "selected_burden_depth":sev.loc[["WV","NY","DC","FL","HI"]].round(2).to_dict("index"), "selected_gaps":example.round(2).to_dict()}} (HERE/"review-values.json").write_text(json.dumps(summary,indent=2,ensure_ascii=False)+"\n",encoding="utf8")