"""Build Crop & County's farm-scale charts from three USDA NASS Census PDFs.""" import hashlib import json import re from pathlib import Path import fitz import matplotlib import pandas as pd matplotlib.use("Agg") import matplotlib.pyplot as plt ROOT = Path(__file__).resolve().parent CHARTS = ROOT / "charts" BASE = "https://www.nass.usda.gov/sites/default/files/publications/agcensus/2022/Full_Report/Volume_1%2C_Chapter_1_US/" HISTORY, SIZES, SALES = "st99_1_001_001.pdf", "st99_1_009_010.pdf", "st99_1_041_041.pdf" COLORS = ["#7e5130", "#2a6451", "#a34646", "#6d5481", "#7a6129"] PLAN = [] def rows(file): with fitz.open(ROOT / file) as document: return [line.strip() for line in document[0].get_text(sort=True).splitlines()] def locate(lines, starts): return next(i for i, line in enumerate(lines) if line.startswith(starts)) def digits(line, n): values = re.findall(r"(?= n, line return [int(item.replace(",", "")) for item in values[-n:]] def inputs(): summary = rows(HISTORY) history = pd.DataFrame({ "Census year": [2022, 2017, 2012, 2007, 2002], "Number of farms": digits(summary[locate(summary, "Farms ...")], 8)[:5], "Land in farms": digits(summary[locate(summary, "Land in farms ...")], 8)[:5], }).sort_values("Census year") detailed = rows(SIZES) start = locate(detailed, "Farms by size") end = locate(detailed, "Farms with harvested cropland") size_data = [(line.split("...")[0].strip(), *digits(line, 8)) for line in detailed[start + 1:end] if line] sizes = pd.DataFrame(size_data, columns=["Acreage category"] + [f"{measure} {year}" for measure in ("Farms", "Land", "Harvested", "Irrigated") for year in (2022, 2017)]) assert len(sizes) == 13 and sizes["Farms 2022"].sum() == 1_900_487 assert sizes["Land 2022"].sum() == 880_100_848 assert sizes["Harvested 2022"].sum() == 301_327_737 assert sizes["Irrigated 2022"].sum() == 54_930_363 sales = rows(SALES) threshold = ["All farms", "10% of sales", "25% of sales", "50% of sales", "75% of sales"] concentration = pd.DataFrame({ "USDA threshold": threshold, "Farms": digits(sales[locate(sales, "Farms ...")], 5), "Land": digits(sales[locate(sales, "Land in farms ...")], 5), "Harvested cropland": digits(sales[locate(sales, "Harvested cropland")], 5), "Sales thousand dollars": digits(sales[locate(sales, "Market value of agricultural products sold")], 5), "Estimated machinery value thousand dollars": digits(sales[locate(sales, "equipment ...")], 5), }) assert concentration.iloc[3]["Farms"] == 26_214 markers = { "Grains and oilseeds": "dry peas ...", "Vegetables and melons": "sweet potatoes ...", "Fruit, nuts and berries": "Fruits, tree nuts, and berries", "Cattle and calves": "Cattle and calves", "Milk from cows": "Milk from cows", "Hogs and pigs": "Hogs and pigs", "Poultry and eggs": "Poultry and eggs", } commodities = pd.DataFrame([ (key, *digits(sales[locate(sales, marker) + 1], 5)) for key, marker in markers.items() ], columns=["Commodity", *threshold]) markers = { "All production expenses": "Total farm production expenses", "Feed": "Feed purchased", "Livestock and poultry purchased or leased": "or leased ...", "Fertilizer, lime and conditioners": "conditioners purchased", "Chemicals": "Chemicals purchased", } expenses = pd.DataFrame([ (key, *digits(sales[locate(sales, marker) + 1], 5)) for key, marker in markers.items() ], columns=["Expense", *threshold]) assert int(expenses["All farms"].iloc[0]) == 424_141_822 assert int(commodities["All farms"].iloc[0]) == 168_712_895 return history, sizes, concentration, commodities, expenses def graph(slug, title, data, measure, *, xlab, source, period, population, question, takeaway, vertical=False): figure, axes = plt.subplots(figsize=(10.4, max(4.6, .46 * len(data) + 2.5)), layout="constrained") figure.set_facecolor("#fbf5e8") axes.set_facecolor("#fbf5e8") axes.set_title(title, loc="left", color="#372b24", fontsize=15, fontweight="bold", pad=13) axes.tick_params(length=0, pad=7, colors="#372b24") for spine in axes.spines.values(): spine.set_visible(False) axes.set_axisbelow(True) if vertical: for key, color in zip(measure, COLORS): axes.plot(data.iloc[:, 0], data[key], marker="o", label=key, color=color, linewidth=2.5) axes.set_xticks(data.iloc[:, 0]) axes.set_ylabel(xlab) axes.set_ylim(82, 106) axes.grid(axis="y", alpha=.2) axes.legend(frameon=False) elif len(measure) == 1: values = data[measure[0]] axes.barh(data.iloc[:, 0], values, height=.59, color=[COLORS[1] if v >= 0 else COLORS[2] for v in values]) axes.invert_yaxis() else: for i, (key, color) in enumerate(zip(measure, COLORS)): offsets = [row + .34 * i for row in range(len(data))] axes.barh(offsets, data[key], height=.29, label=key, color=color) axes.set_yticks([row + .17 * (len(measure) - 1) for row in range(len(data))], data.iloc[:, 0]) axes.invert_yaxis() axes.legend(frameon=False) if not vertical: axes.set_xlabel(xlab) axes.axvline(0, color="#40342a", linewidth=.6) axes.grid(axis="x", alpha=.2) figure.text(.018, .015, "USDA NASS 2022 Census of Agriculture", fontsize=8.8, color="#372b24") figure.get_layout_engine().set(rect=(.014, .067, .97, .9)) figure.savefig(CHARTS / f"{slug}.png", dpi=135, facecolor=figure.get_facecolor()) plt.close(figure) data.to_csv(CHARTS / f"{slug}.csv", index=False) PLAN.append(dict(asset=f"charts/{slug}.png", data=f"charts/{slug}.csv", title=title, question=question, source=BASE + source, population=population, period=period, unit=xlab, takeaway=takeaway)) def main(): CHARTS.mkdir(exist_ok=True) history, size, concentration, commodities, expenses = inputs() for file, table in (("history",history), ("size-bands",size), ("sales-thresholds",concentration), ("commodity-sales",commodities), ("production-expenses",expenses)): table.to_csv(ROOT / f"{file}.csv", index=False) trend = history.astype({"Number of farms": float, "Land in farms": float}) trend.iloc[:, 1:] = 100 * trend.iloc[:, 1:].div(trend.iloc[0, 1:]) graph("chart-01-farms-and-land", "The number of farms fell faster than land in farms", trend, ["Number of farms", "Land in farms"], xlab="Index, 2002 = 100", source=HISTORY, period="2002–2022", population="All U.S. farms included in USDA's national Census of Agriculture", question="Which decreased more over 20 years?", takeaway="Farm count declined 10.7% and land in farms 6.2% from 2002 to 2022.", vertical=True) bands = ["Under 50 acres"]*2 + ["50–179 acres"]*4 + ["180–499 acres"]*3 + ["500–1,999 acres"]*2 + ["2,000–4,999 acres","5,000 acres or more"] grouped = size.assign(Group=bands).groupby("Group", sort=False).sum(numeric_only=True) farm_change = grouped[["Farms 2022"]].reset_index().rename(columns={"Farms 2022":"Change"}) farm_change["Change"] = (grouped["Farms 2022"] - grouped["Farms 2017"]).values / 1_000 graph("chart-02-farms-by-size-change", "Only the largest of these acreage bands gained farms", farm_change, ["Change"], xlab="Change in thousands of farms", source=SIZES, period="2017–2022", population="U.S. farms grouped by acres of land in operation", question="Which acreage bands gained or lost farm operations?", takeaway="Farms of 5,000 acres or more gained 1,349 operations.") shares = grouped[["Farms 2022","Land 2022"]].div(grouped[["Farms 2022","Land 2022"]].sum()).mul(100).reset_index() graph("chart-03-farm-and-acre-shares", "The farm count and acreage emphasize different bands", shares, ["Farms 2022","Land 2022"], xlab="Percent of the corresponding U.S. total", source=SIZES, period="2022", population="U.S. farms, and land in farms, using their own national denominators", question="What changes when acreage replaces operations?", takeaway="Farms under 50 acres are 42.2% of operations; farms of 5,000 acres or more report 41.8% of land in farms.") acre_change = grouped[["Land 2022"]].reset_index().rename(columns={"Land 2022":"Change"}) acre_change["Change"] = (grouped["Land 2022"] - grouped["Land 2017"]).values / 1_000_000 graph("chart-04-land-change-by-size", "The 5,000-acre-and-up band added land as the total shrank", acre_change, ["Change"], xlab="Change in millions of acres", source=SIZES, period="2017–2022", population="Total land in U.S. farms by operation acreage band", question="Did farm acreage decrease in every band?", takeaway="The top acreage band added 25.8 million acres while all other bands combined lost 45.9 million.") large = grouped.tail(2) land_use = [] for label, measure in [("All land in farms","Land"),("Harvested cropland","Harvested"),("Irrigated land","Irrigated")]: land_use.append((label, *[large[f"{measure} {y}"].sum()*100/grouped[f"{measure} {y}"].sum() for y in [2017,2022]])) graph("chart-05-large-farm-land-use", "Larger farms had at least half of each acre measure in 2022", pd.DataFrame(land_use, columns=["National acre measure","2017","2022"]), ["2017","2022"], xlab="Percent on farms with at least 2,000 acres", source=SIZES, period="2017 and 2022", population="All reported U.S. farm acres, harvested cropland acres and irrigated acres", question="Does the large-farm share also appear in harvested and irrigated acreage?", takeaway="The large-farm shares rose for land in farms, harvested cropland and irrigated land.") threshold_shares = concentration.astype({column: float for column in concentration.columns[1:]}) threshold_shares.iloc[:, 1:] = 100 * threshold_shares.iloc[:, 1:].div(threshold_shares.iloc[0, 1:].astype(float)) threshold_shares = threshold_shares.iloc[1:].rename(columns={"Sales thousand dollars":"Farm-product sales"}) graph("chart-06-sales-concentration", "Half of sales came from 1.4% of farms", threshold_shares, ["Farms","Land","Farm-product sales"], xlab="Percent of U.S. total", source=SALES, period="2022", population="Nested groups of farms ranked by total market value of agricultural products sold", question="How many farms account for the USDA sales thresholds?", takeaway="The 26,214 farms in the 50% sales cohort had 10.1% of land in U.S. farms.") selected = commodities[["Commodity"]].copy() selected["Share"] = commodities["50% of sales"].div(commodities["All farms"]).mul(100) selected = selected.sort_values("Share", ascending=False) graph("chart-07-commodity-mix", "The same 26,214 farms had different shares across products", selected, ["Share"], xlab="Percent of U.S. market value for each commodity group", source=SALES, period="2022", population="Farms ranked by overall sales until reaching half of U.S. farm-product sales", question="Which kinds of products contribute most to the top-sales cohort?", takeaway="The cohort accounted for 77.6% of vegetable-group sales and 22.5% of grain-group sales.") spending = expenses[["Expense"]].copy() spending["Share"] = expenses["50% of sales"].div(expenses["All farms"]).mul(100) spending = spending.sort_values("Share", ascending=False) graph("chart-08-production-expense-shares", "Spending concentration varied across inputs", spending, ["Share"], xlab="Percent of U.S. expenses in each category", source=SALES, period="2022", population="Farms ranked by overall sales until reaching half of U.S. farm-product sales", question="Did the high-sales cohort represent the same share of every cost?", takeaway="The high-sales group accounted for 69.3% of livestock and poultry purchases and 27.4% of fertilizer expenses.") inventory = [{"file":name, "url":BASE + name, "sha256":hashlib.sha256((ROOT/name).read_bytes()).hexdigest()} for name in (HISTORY,SIZES,SALES)] (ROOT / "source-manifest.json").write_text(json.dumps(inventory, indent=2) + "\n", encoding="utf-8") (ROOT / "CHART-PLAN.json").write_text(json.dumps(PLAN, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") if __name__ == "__main__": main()