"""Render the public ZIP comparison. Requires matplotlib 3.10.x.""" import csv import json from pathlib import Path import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.ticker import PercentFormatter HERE = Path(__file__).resolve().parent DATA = HERE / "results" if (HERE / "results").is_dir() else HERE OUT = HERE / "figures" OUT.mkdir(exist_ok=True) plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 12, "svg.hashsalt": "acd-zip-business-income-v1", "axes.spines.top": False, "axes.spines.right": False, "axes.edgecolor": "#64716a", "text.color": "#202d25", "axes.labelcolor": "#202d25", "savefig.facecolor": "white"}) GREEN, BLUE = "#107C41", "#315a92" summary = json.loads((DATA / "summary.json").read_text()) groups = summary["main"]["groups"] with (DATA / "zip_comparison.csv").open(newline="") as f: rows = [r for r in csv.DictReader(f) if r["main_sample"] == "yes"] assert len(rows) == summary["main"]["zip_codes"] assert all(-50 <= float(r["establishment_change_pct"]) <= 150 and all(-80 <= float(r[field]) <= 185 for field in ("return_change_pct", "mean_agi_change_pct")) for r in rows), "Expand the reviewed axes before rendering; never hide an outlier." def save(fig, name, mobile): svg = OUT / (name + ("-mobile" if mobile else "") + ".svg") fig.savefig(svg, metadata={"Date": None}) svg.write_text("\n".join(line.rstrip() for line in svg.read_text().splitlines()) + "\n") if not mobile: fig.savefig(OUT / (name + ".png"), dpi=160, metadata={"Software": "Actually Clean Data / matplotlib"}) plt.close(fig) for mobile in (False, True): fig, ax = plt.subplots(figsize=(6.2, 7.8) if mobile else (10.8, 6.4)) fig.subplots_adjust(left=.32 if mobile else .26, right=.93, bottom=.28 if mobile else .24, top=.79) for index, g in enumerate(groups): for offset, field, color in [(-.17, "return_change_pct", GREEN), (.17, "mean_agi_change_pct", BLUE)]: value = g[field] ax.barh(index + offset, value, height=.29, color=color) ax.text(value + .5, index + offset, f"{value:.1f}%", va="center", fontsize=11) ax.set_yticks(range(4), [g["group"] + "\n" + f"{g['zip_codes']:,} ZIPs" for g in groups]) ax.invert_yaxis(); ax.set_xlim(0, 34); ax.xaxis.set_major_formatter(PercentFormatter(100)) ax.set_xlabel("Median change, 2018–2023") ax.grid(axis="x", color="#dce4df", linewidth=.6); ax.set_axisbelow(True) fig.suptitle("More business locations and\nchanges in the tax-filing population" if mobile else "Business growth was accompanied by more tax filers", x=.05, y=.96, ha="left", fontsize=17, weight="bold") fig.text(.05, .85, "Groups are based on employer establishment growth.", fontsize=10) fig.legend([plt.Rectangle((0, 0), 1, 1, color=GREEN), plt.Rectangle((0, 0), 1, 1, color=BLUE)], ["Number of tax returns", "Mean AGI per return (nominal)"], loc="lower left", bbox_to_anchor=(.04, .13), frameon=False, ncol=1 if mobile else 2, fontsize=10) footer = "12,649 ZIPs: at least 100 establishments and 1,000 returns in 2018.\nEach ZIP has equal weight. Income is not adjusted for inflation.\nSources: Census ZBP, IRS SOI; Actually Clean Data calculations." if mobile: footer = "12,649 ZIPs: ≥100 establishments and ≥1,000 returns in 2018.\nZIPs weighted equally; nominal income.\nSources: Census ZBP, IRS SOI; Actually Clean Data." fig.text(.05, .035, footer, fontsize=9, linespacing=1.5) save(fig, "growth-groups", mobile) fig, axes = plt.subplots(2 if mobile else 1, 1 if mobile else 2, figsize=(6.2, 10.8) if mobile else (11.8, 6.3)) fig.subplots_adjust(left=.13 if mobile else .08, right=.95, top=.85 if mobile else .79, bottom=.17 if mobile else .25, hspace=.42, wspace=.25) x = [float(r["establishment_change_pct"]) for r in rows] for ax, field, label, color in zip(axes.flat, ["return_change_pct", "mean_agi_change_pct"], ["Tax-return count", "Mean AGI per return (nominal)"], [GREEN, BLUE]): y = [float(r[field]) for r in rows] ax.scatter(x, y, s=6, alpha=.15, color=color, linewidth=0, rasterized=True) ax.axhline(0, color="#8e9d94", linewidth=.65); ax.axvline(0, color="#8e9d94", linewidth=.65) ax.set_xlim(-50, 150); ax.set_ylim(-80, 185) if mobile: ax.set_xticks([-50, 0, 50, 100, 150]) ax.xaxis.set_major_formatter(PercentFormatter(100)); ax.yaxis.set_major_formatter(PercentFormatter(100)) ax.set_xlabel("Establishment change"); ax.set_ylabel("Change, 2018–2023") ax.set_title(label + "\n" + f"Rank correlation: {summary['main'][field + '_spearman']:.2f}", fontsize=11, loc="left") if mobile: fig.subplots_adjust(left=.21) fig.suptitle("The return-count relationship is stronger" if not mobile else "Business growth, tax returns\nand average income", x=.05, y=.96, ha="left", fontsize=17, weight="bold") footer = "Each point is one of the same 12,649 ZIP codes. All points shown; no outliers removed.\n2018–2023 changes. ≥100 establishments and ≥1,000 tax returns at baseline; nominal AGI.\nPostal boundaries and filers can change. Association does not establish cause.\nSources: Census ZBP, IRS SOI; calculations by Actually Clean Data." if mobile: footer = "All 12,649 ZIPs shown; no outliers removed.\n2018–2023; ≥100 establishments and ≥1,000 returns in 2018.\nNominal AGI. Boundaries and filers can change.\nAssociation does not establish cause.\nSources: Census ZBP, IRS SOI; Actually Clean Data." fig.text(.05, .035, footer, fontsize=9, linespacing=1.5) save(fig, "growth-scatter", mobile) print("Rendered six figures from", len(rows), "ZIP comparisons.")