stplot 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. stplot/__init__.py +21 -0
  2. stplot/config/__init__.py +33 -0
  3. stplot/config/loader.py +106 -0
  4. stplot/config/models.py +328 -0
  5. stplot/config/presets/__init__.py +1 -0
  6. stplot/config/presets/default.yaml +208 -0
  7. stplot/config/presets/horizons_one_plan.yaml +59 -0
  8. stplot/io/__init__.py +6 -0
  9. stplot/io/spatial.py +72 -0
  10. stplot/io/tabular.py +154 -0
  11. stplot/plots/__init__.py +122 -0
  12. stplot/plots/barbell.py +400 -0
  13. stplot/plots/batch.py +135 -0
  14. stplot/plots/domains.py +1143 -0
  15. stplot/plots/executive.py +474 -0
  16. stplot/plots/export.py +74 -0
  17. stplot/plots/infographics.py +1118 -0
  18. stplot/plots/lollipop.py +285 -0
  19. stplot/plots/maps.py +738 -0
  20. stplot/plots/matrix.py +190 -0
  21. stplot/plots/one_plan.py +642 -0
  22. stplot/plots/paired.py +437 -0
  23. stplot/plots/scorecards.py +1940 -0
  24. stplot/plots/state.py +373 -0
  25. stplot/plots/state_trends.py +1413 -0
  26. stplot/plots/tables.py +107 -0
  27. stplot/plots/timeseries.py +607 -0
  28. stplot/plots/trends.py +305 -0
  29. stplot/reporting/__init__.py +24 -0
  30. stplot/reporting/captions.py +177 -0
  31. stplot/reporting/html_companion.py +339 -0
  32. stplot/reporting/templates.py +485 -0
  33. stplot/reporting/word.py +369 -0
  34. stplot/theme/__init__.py +25 -0
  35. stplot/theme/folium.py +62 -0
  36. stplot/theme/mpl.py +181 -0
  37. stplot/theme/plotly.py +130 -0
  38. stplot/transform/__init__.py +60 -0
  39. stplot/transform/categories.py +51 -0
  40. stplot/transform/columns.py +103 -0
  41. stplot/transform/filters.py +385 -0
  42. stplot/transform/merge.py +173 -0
  43. stplot/transform/pairing.py +154 -0
  44. stplot/transform/qa.py +297 -0
  45. stplot/transform/tables.py +573 -0
  46. stplot/transform/zones.py +354 -0
  47. stplot-0.1.0.dist-info/METADATA +235 -0
  48. stplot-0.1.0.dist-info/RECORD +49 -0
  49. stplot-0.1.0.dist-info/WHEEL +4 -0
@@ -0,0 +1,1118 @@
1
+ """Publication-ready infographic templates for public, councillor, and report summaries."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import textwrap
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import matplotlib.pyplot as plt
11
+ import numpy as np
12
+ import pandas as pd
13
+ from matplotlib.axes import Axes
14
+ from matplotlib.figure import Figure
15
+ from matplotlib.gridspec import GridSpec
16
+ from matplotlib.patches import FancyBboxPatch, Wedge
17
+
18
+ from stplot.config import (
19
+ Config,
20
+ ensure_config,
21
+ resolve_category_order,
22
+ resolve_column,
23
+ resolve_label,
24
+ resolve_palette,
25
+ )
26
+ from stplot.plots.maps import publication_map
27
+ from stplot.theme.mpl import mpl_theme
28
+ from stplot.transform.columns import validate_columns
29
+ from stplot.transform.filters import derive_trend_direction_3level
30
+
31
+
32
+ def _contrast_text(hex_color: str) -> str:
33
+ cleaned = hex_color.lstrip("#")
34
+ if len(cleaned) != 6:
35
+ return "#1e2a38"
36
+ r, g, b = int(cleaned[0:2], 16), int(cleaned[2:4], 16), int(cleaned[4:6], 16)
37
+ return "#111111" if (0.299 * r + 0.587 * g + 0.114 * b) > 150 else "#ffffff"
38
+
39
+
40
+ def catchment_profile_infographic(
41
+ df: pd.DataFrame,
42
+ *,
43
+ site_col: str | None = None,
44
+ order_col: str = "Site.Order.in.catchment.(Report)",
45
+ band_col: str | None = None,
46
+ value_col: str | None = None,
47
+ value_unit: str = "",
48
+ palette: dict[str, str] | None = None,
49
+ title: str = "Mountains-to-Sea Catchment Profile",
50
+ subtitle: str | None = None,
51
+ upstream_label: str = "Headwaters",
52
+ downstream_label: str = "Coast / Estuary",
53
+ figsize: tuple[float, float] | None = None,
54
+ ax: Axes | None = None,
55
+ config: str | Path | Config | None = None,
56
+ ) -> tuple[Figure, Axes]:
57
+ """Plot a Mountains-to-Sea river continuum profile ordered from headwaters to coast.
58
+
59
+ Displays sites sequentially along a flowing river ribbon colored by NPS-FM NOF Grade,
60
+ with alternating above/below callouts showing site name and optional numeric value.
61
+
62
+ Returns:
63
+ Tuple of ``(fig, ax)``.
64
+ """
65
+ cfg = ensure_config(config)
66
+ resolved_site = resolve_column(site_col, cfg, "site_id")
67
+ resolved_band = resolve_column(band_col, cfg, "state_band")
68
+ validate_columns(df, [resolved_site, resolved_band], context="catchment_profile_infographic")
69
+
70
+ work = df.copy()
71
+ if order_col in work.columns:
72
+ work["_ord"] = pd.to_numeric(work[order_col], errors="coerce")
73
+ work = work.sort_values(by="_ord", kind="stable").reset_index(drop=True)
74
+ else:
75
+ work = work.reset_index(drop=True)
76
+
77
+ resolved_pal = resolve_palette(palette, cfg, "state_bands")
78
+ n = len(work)
79
+ if n == 0:
80
+ raise ValueError("catchment_profile_infographic: Input DataFrame is empty.")
81
+
82
+ with mpl_theme(cfg):
83
+ if ax is None:
84
+ fig_w = max(11.0, 1.35 * n + 2.0)
85
+ fig, ax = plt.subplots(figsize=figsize or (fig_w, 5.4))
86
+ else:
87
+ fig = ax.figure # type: ignore[assignment]
88
+
89
+ ax.set_facecolor(cfg.theme.background_color)
90
+ xs = np.linspace(0.8, max(n - 0.2, 1.8), n)
91
+ x_smooth = np.linspace(xs[0] - 0.55, xs[-1] + 0.55, 300)
92
+ y_smooth = 0.22 * np.sin(np.linspace(0, 2.2 * np.pi, 300))
93
+
94
+ # Flowing river ribbon (outer soft halo + inner river blue)
95
+ ax.plot(x_smooth, y_smooth, color="#d6eef8", linewidth=22, solid_capstyle="round", zorder=1)
96
+ ax.plot(x_smooth, y_smooth, color="#7ec8e3", linewidth=10, solid_capstyle="round", zorder=2)
97
+
98
+ # Flow direction arrows along ribbon
99
+ ax.annotate(
100
+ "",
101
+ xy=(x_smooth[-1] + 0.15, y_smooth[-1]),
102
+ xytext=(x_smooth[-1] - 0.25, y_smooth[-1]),
103
+ arrowprops={"arrowstyle": "-|>", "color": "#0077a3", "lw": 2.4},
104
+ zorder=3,
105
+ )
106
+
107
+ ax.text(
108
+ x_smooth[0],
109
+ -1.08,
110
+ f"◀ {upstream_label}",
111
+ ha="left",
112
+ va="center",
113
+ fontsize=cfg.theme.caption_size,
114
+ fontweight="bold",
115
+ color="#0077a3",
116
+ )
117
+ ax.text(
118
+ x_smooth[-1],
119
+ -1.08,
120
+ f"{downstream_label} ▶",
121
+ ha="right",
122
+ va="center",
123
+ fontsize=cfg.theme.caption_size,
124
+ fontweight="bold",
125
+ color="#0077a3",
126
+ )
127
+
128
+ # Site milestone nodes and alternating callouts
129
+ for idx, row in work.iterrows():
130
+ x = float(xs[idx])
131
+ y = float(np.interp(x, x_smooth, y_smooth))
132
+ band = str(row[resolved_band])
133
+ color = resolved_pal.get(band, "#bdbdbd")
134
+ site_name = resolve_label(str(row[resolved_site]), cfg)
135
+
136
+ ax.scatter(
137
+ x,
138
+ y,
139
+ s=520,
140
+ color=color,
141
+ edgecolors="#1e2a38",
142
+ linewidths=1.6,
143
+ zorder=5,
144
+ )
145
+ ax.text(
146
+ x,
147
+ y,
148
+ band,
149
+ ha="center",
150
+ va="center",
151
+ fontsize=11,
152
+ fontweight="bold",
153
+ color=_contrast_text(color),
154
+ zorder=6,
155
+ )
156
+
157
+ above = idx % 2 == 0
158
+ y_label = y + 0.62 if above else y - 0.62
159
+ ax.plot(
160
+ [x, x],
161
+ [y + (0.14 if above else -0.14), y_label - (0.08 if above else -0.08)],
162
+ color=cfg.theme.spine_color,
163
+ linewidth=1.1,
164
+ linestyle="--",
165
+ zorder=3,
166
+ )
167
+
168
+ wrapped = "\n".join(textwrap.wrap(site_name, width=18))
169
+ if value_col and value_col in work.columns and pd.notna(row[value_col]):
170
+ val_txt = f"{float(row[value_col]):.3g}"
171
+ if value_unit:
172
+ val_txt = f"{val_txt} {value_unit}"
173
+ wrapped = f"{wrapped}\n({val_txt})"
174
+
175
+ ax.text(
176
+ x,
177
+ y_label,
178
+ wrapped,
179
+ ha="center",
180
+ va="bottom" if above else "top",
181
+ fontsize=cfg.theme.caption_size,
182
+ color=cfg.theme.text_color,
183
+ fontweight="bold" if idx in {0, n - 1} else "normal",
184
+ zorder=6,
185
+ )
186
+
187
+ ax.set_xlim(x_smooth[0] - 0.35, x_smooth[-1] + 0.45)
188
+ ax.set_ylim(-1.35, 1.35)
189
+ ax.axis("off")
190
+
191
+ fig.suptitle(
192
+ title,
193
+ fontsize=cfg.theme.title_size + 1,
194
+ fontweight=cfg.theme.title_weight,
195
+ color=cfg.theme.text_color,
196
+ y=0.97,
197
+ )
198
+ if subtitle:
199
+ fig.text(
200
+ 0.5,
201
+ 0.90,
202
+ subtitle,
203
+ ha="center",
204
+ va="top",
205
+ fontsize=cfg.theme.subtitle_size,
206
+ color=cfg.theme.caption_color,
207
+ )
208
+
209
+ return fig, ax
210
+
211
+
212
+ def site_report_card(
213
+ df: pd.DataFrame,
214
+ *,
215
+ site_name: str,
216
+ fmu_name: str | None = None,
217
+ period: str | None = None,
218
+ indicator_col: str | None = None,
219
+ band_col: str | None = None,
220
+ trend_col: str | None = None,
221
+ value_col: str | None = None,
222
+ palette: dict[str, str] | None = None,
223
+ trend_palette: dict[str, str] | None = None,
224
+ figsize: tuple[float, float] | None = None,
225
+ config: str | Path | Config | None = None,
226
+ ) -> tuple[Figure, Axes]:
227
+ """Render a LAWA-style single-site report card with NOF Grade badges and trend pills.
228
+
229
+ Args:
230
+ df: DataFrame with one row per indicator for the target site.
231
+ site_name: Site display title shown in the header banner.
232
+ fmu_name: Optional FMU / catchment subtitle.
233
+ period: Optional reporting period label (e.g., ``"2021–2025"``).
234
+ indicator_col: Indicator column override (defaults to ``config.columns["indicator"]``).
235
+ band_col: State band column override (defaults to ``config.columns["state_band"]``).
236
+ trend_col: Optional trend direction column (``Improving`` / ``Indeterminate`` /
237
+ ``Degrading``).
238
+ value_col: Optional numeric metric value shown beneath each badge.
239
+ palette: Optional state band color mapping override.
240
+ trend_palette: Optional trend direction color mapping override.
241
+ figsize: Optional ``(width, height)`` override.
242
+ config: Optional Config object, preset name, or path to YAML/TOML config.
243
+
244
+ Returns:
245
+ Tuple of ``(fig, ax)``.
246
+ """
247
+ cfg = ensure_config(config)
248
+ resolved_ind = resolve_column(indicator_col, cfg, "indicator")
249
+ resolved_band = resolve_column(band_col, cfg, "state_band")
250
+ validate_columns(df, [resolved_ind, resolved_band], context="site_report_card")
251
+
252
+ state_pal = resolve_palette(palette, cfg, "state_bands")
253
+ tr_pal = resolve_palette(trend_palette, cfg, "trend_directions")
254
+
255
+ work = df.copy().reset_index(drop=True)
256
+ n = len(work)
257
+ if n == 0:
258
+ raise ValueError("site_report_card: Input DataFrame is empty.")
259
+
260
+ trend_symbols = {"Improving": "↗", "Indeterminate": "→", "Degrading": "↘"}
261
+
262
+ with mpl_theme(cfg):
263
+ fig_w = max(9.0, 2.05 * n + 0.8)
264
+ fig, ax = plt.subplots(figsize=figsize or (fig_w, 4.3))
265
+ fig.patch.set_facecolor(cfg.theme.background_color)
266
+ ax.set_xlim(0, n)
267
+ ax.set_ylim(0, 1.0)
268
+ ax.axis("off")
269
+
270
+ # Top branded header banner
271
+ banner = FancyBboxPatch(
272
+ (0.08, 0.76),
273
+ n - 0.16,
274
+ 0.20,
275
+ boxstyle="round,pad=0.02,rounding_size=0.04",
276
+ facecolor="#263742",
277
+ edgecolor="none",
278
+ )
279
+ ax.add_patch(banner)
280
+ ax.text(
281
+ 0.24,
282
+ 0.885,
283
+ resolve_label(site_name, cfg),
284
+ ha="left",
285
+ va="center",
286
+ fontsize=cfg.theme.title_size + 1,
287
+ fontweight="bold",
288
+ color="#ffffff",
289
+ )
290
+ meta_parts = [p for p in (fmu_name, period) if p]
291
+ if meta_parts:
292
+ ax.text(
293
+ 0.24,
294
+ 0.805,
295
+ " | ".join(resolve_label(p, cfg) for p in meta_parts),
296
+ ha="left",
297
+ va="center",
298
+ fontsize=cfg.theme.caption_size + 0.5,
299
+ color="#cfd8dc",
300
+ )
301
+
302
+ # Indicator badge cards
303
+ for idx, row in work.iterrows():
304
+ cx = idx + 0.5
305
+ card = FancyBboxPatch(
306
+ (idx + 0.08, 0.06),
307
+ 0.84,
308
+ 0.63,
309
+ boxstyle="round,pad=0.02,rounding_size=0.04",
310
+ facecolor="#f8fafc",
311
+ edgecolor=cfg.theme.spine_color,
312
+ linewidth=1.0,
313
+ )
314
+ ax.add_patch(card)
315
+
316
+ ind_lbl = resolve_label(str(row[resolved_ind]), cfg)
317
+ ax.text(
318
+ cx,
319
+ 0.61,
320
+ "\n".join(textwrap.wrap(ind_lbl, width=15)),
321
+ ha="center",
322
+ va="center",
323
+ fontsize=cfg.theme.tick_size - 0.5,
324
+ fontweight="bold",
325
+ color=cfg.theme.text_color,
326
+ )
327
+
328
+ band = str(row[resolved_band])
329
+ b_color = state_pal.get(band, "#bdbdbd")
330
+ badge = FancyBboxPatch(
331
+ (cx - 0.22, 0.30),
332
+ 0.44,
333
+ 0.20,
334
+ boxstyle="round,pad=0.02,rounding_size=0.05",
335
+ facecolor=b_color,
336
+ edgecolor="#1e2a38",
337
+ linewidth=0.9,
338
+ )
339
+ ax.add_patch(badge)
340
+ ax.text(
341
+ cx,
342
+ 0.40,
343
+ band,
344
+ ha="center",
345
+ va="center",
346
+ fontsize=18,
347
+ fontweight="bold",
348
+ color=_contrast_text(b_color),
349
+ )
350
+
351
+ if value_col and value_col in work.columns and pd.notna(row[value_col]):
352
+ ax.text(
353
+ cx,
354
+ 0.23,
355
+ f"Median: {float(row[value_col]):.3g}",
356
+ ha="center",
357
+ va="center",
358
+ fontsize=cfg.theme.caption_size - 0.8,
359
+ color=cfg.theme.caption_color,
360
+ )
361
+
362
+ if trend_col and trend_col in work.columns and pd.notna(row[trend_col]):
363
+ tr_val = str(row[trend_col])
364
+ tr_col = tr_pal.get(tr_val, "#bdbdbd")
365
+ pill = FancyBboxPatch(
366
+ (cx - 0.34, 0.09),
367
+ 0.68,
368
+ 0.09,
369
+ boxstyle="round,pad=0.01,rounding_size=0.03",
370
+ facecolor=tr_col,
371
+ edgecolor="none",
372
+ alpha=0.9,
373
+ )
374
+ ax.add_patch(pill)
375
+ sym = trend_symbols.get(tr_val, "")
376
+ ax.text(
377
+ cx,
378
+ 0.135,
379
+ f"{sym} {tr_val}".strip(),
380
+ ha="center",
381
+ va="center",
382
+ fontsize=cfg.theme.caption_size - 1.0,
383
+ fontweight="bold",
384
+ color=_contrast_text(tr_col),
385
+ )
386
+
387
+ fig.tight_layout()
388
+
389
+ return fig, ax
390
+
391
+
392
+ def catchment_report_card(
393
+ state_df: pd.DataFrame,
394
+ *,
395
+ catchment_name: str,
396
+ trend_df: pd.DataFrame | None = None,
397
+ period: str = "2021–2025",
398
+ indicator_col: str | None = None,
399
+ band_col: str | None = None,
400
+ site_col: str | None = None,
401
+ ncols: int = 3,
402
+ palette: dict[str, str] | None = None,
403
+ trend_palette: dict[str, str] | None = None,
404
+ figsize: tuple[float, float] | None = None,
405
+ config: str | Path | Config | None = None,
406
+ ) -> tuple[Figure, list[Axes]]:
407
+ """Render a Catchment / FMU Report Card summarizing state bands and trends per indicator.
408
+
409
+ Displays a branded catchment header banner (name, total unique sites, period) above
410
+ a multi-column grid of indicator cards — each showing a 100% horizontal NOF grade
411
+ bar, ``% Band A/B`` headline readout, and optional ``% Improving`` / ``% Degrading``
412
+ trend summary.
413
+
414
+ Returns:
415
+ Tuple of ``(fig, axes_list)``.
416
+ """
417
+ cfg = ensure_config(config)
418
+ resolved_ind = resolve_column(indicator_col, cfg, "indicator")
419
+ resolved_band = resolve_column(band_col, cfg, "state_band")
420
+ resolved_site = site_col if site_col is not None else cfg.columns.get("site_id")
421
+ validate_columns(state_df, [resolved_ind, resolved_band], context="catchment_report_card")
422
+
423
+ state_pal = resolve_palette(palette, cfg, "state_bands")
424
+ tr_pal = resolve_palette(trend_palette, cfg, "trend_directions")
425
+ band_order = [
426
+ b
427
+ for b in resolve_category_order(None, cfg, "state_bands")
428
+ if b in {"A", "B", "C", "D", "E"}
429
+ ]
430
+
431
+ indicators = list(dict.fromkeys(state_df[resolved_ind].dropna().astype(str).tolist()))
432
+ n_ind = len(indicators)
433
+ if n_ind == 0:
434
+ raise ValueError("catchment_report_card: No indicators found in state_df.")
435
+
436
+ n_sites = (
437
+ int(state_df[resolved_site].nunique())
438
+ if resolved_site and resolved_site in state_df.columns
439
+ else len(state_df)
440
+ )
441
+
442
+ tr_work = None
443
+ if trend_df is not None and not trend_df.empty and resolved_ind in trend_df.columns:
444
+ tr_work = derive_trend_direction_3level(trend_df, out_col="_tr_3", config=cfg)
445
+
446
+ n_cols = min(ncols, n_ind)
447
+ n_rows = math.ceil(n_ind / n_cols)
448
+
449
+ with mpl_theme(cfg):
450
+ fig_size = figsize or (3.9 * n_cols, 2.35 * n_rows + 1.55)
451
+ fig = plt.figure(figsize=fig_size)
452
+ fig.patch.set_facecolor(cfg.theme.background_color)
453
+
454
+ gs = GridSpec(
455
+ n_rows + 1,
456
+ n_cols,
457
+ figure=fig,
458
+ height_ratios=[0.52, *([1.0] * n_rows)],
459
+ hspace=0.25,
460
+ wspace=0.14,
461
+ )
462
+
463
+ # Header banner across top row
464
+ ax_hdr = fig.add_subplot(gs[0, :])
465
+ ax_hdr.set_xlim(0, 1)
466
+ ax_hdr.set_ylim(0, 1)
467
+ ax_hdr.axis("off")
468
+ hdr_box = FancyBboxPatch(
469
+ (0.0, 0.08),
470
+ 1.0,
471
+ 0.86,
472
+ boxstyle="round,pad=0.01,rounding_size=0.04",
473
+ facecolor="#263742",
474
+ edgecolor="none",
475
+ )
476
+ ax_hdr.add_patch(hdr_box)
477
+ ax_hdr.text(
478
+ 0.025,
479
+ 0.64,
480
+ f"{resolve_label(catchment_name, cfg)} — Catchment Report Card",
481
+ ha="left",
482
+ va="center",
483
+ fontsize=cfg.theme.title_size + 2,
484
+ fontweight="bold",
485
+ color="#ffffff",
486
+ )
487
+ ax_hdr.text(
488
+ 0.025,
489
+ 0.27,
490
+ f"Reporting Period: {period} | {n_sites} Monitoring Sites | {n_ind} Indicators",
491
+ ha="left",
492
+ va="center",
493
+ fontsize=cfg.theme.caption_size + 0.8,
494
+ color="#cfd8dc",
495
+ )
496
+
497
+ card_axes: list[Axes] = []
498
+ for idx in range(n_rows * n_cols):
499
+ r, c = divmod(idx, n_cols)
500
+ ax = fig.add_subplot(gs[r + 1, c])
501
+ ax.set_xlim(0, 1)
502
+ ax.set_ylim(0, 1)
503
+ ax.axis("off")
504
+ if idx >= n_ind:
505
+ continue
506
+ card_axes.append(ax)
507
+
508
+ ind = indicators[idx]
509
+ sub = state_df[state_df[resolved_ind].astype(str) == ind]
510
+ counts = sub[resolved_band].astype(str).value_counts()
511
+ total = int(sum(counts.get(b, 0) for b in band_order))
512
+ pct_ab = 100.0 * (counts.get("A", 0) + counts.get("B", 0)) / total if total > 0 else 0.0
513
+
514
+ box = FancyBboxPatch(
515
+ (0.02, 0.04),
516
+ 0.96,
517
+ 0.92,
518
+ boxstyle="round,pad=0.02,rounding_size=0.05",
519
+ facecolor="#f8fafc",
520
+ edgecolor=cfg.theme.spine_color,
521
+ linewidth=1.0,
522
+ )
523
+ ax.add_patch(box)
524
+
525
+ ind_title = resolve_label(ind, cfg)
526
+ title_fs = cfg.theme.label_size - (1.4 if len(ind_title) > 22 else 0.3)
527
+ ax.text(
528
+ 0.08,
529
+ 0.84,
530
+ ind_title,
531
+ ha="left",
532
+ va="center",
533
+ fontsize=title_fs,
534
+ fontweight="bold",
535
+ color=cfg.theme.text_color,
536
+ )
537
+ ax.text(
538
+ 0.92,
539
+ 0.84,
540
+ f"n = {total}",
541
+ ha="right",
542
+ va="center",
543
+ fontsize=cfg.theme.caption_size - 0.5,
544
+ color=cfg.theme.caption_color,
545
+ )
546
+
547
+ ax.text(
548
+ 0.08,
549
+ 0.62,
550
+ f"{pct_ab:.0f}%",
551
+ ha="left",
552
+ va="center",
553
+ fontsize=19,
554
+ fontweight="bold",
555
+ color=cfg.theme.accent_color,
556
+ )
557
+ ax.text(
558
+ 0.36,
559
+ 0.62,
560
+ "in Band A or B",
561
+ ha="left",
562
+ va="center",
563
+ fontsize=cfg.theme.caption_size,
564
+ color=cfg.theme.caption_color,
565
+ )
566
+
567
+ # Mini 100% horizontal stacked bar of bands A-E
568
+ x_cur = 0.08
569
+ bar_w = 0.84
570
+ for b in band_order:
571
+ frac = counts.get(b, 0) / total if total > 0 else 0.0
572
+ if frac <= 0:
573
+ continue
574
+ seg_w = bar_w * frac
575
+ seg = FancyBboxPatch(
576
+ (x_cur, 0.34),
577
+ seg_w,
578
+ 0.14,
579
+ boxstyle="square,pad=0",
580
+ facecolor=state_pal.get(b, "#bdbdbd"),
581
+ edgecolor="#ffffff",
582
+ linewidth=0.8,
583
+ )
584
+ ax.add_patch(seg)
585
+ if frac >= 0.14:
586
+ ax.text(
587
+ x_cur + seg_w / 2.0,
588
+ 0.41,
589
+ b,
590
+ ha="center",
591
+ va="center",
592
+ fontsize=8.5,
593
+ fontweight="bold",
594
+ color=_contrast_text(state_pal.get(b, "#bdbdbd")),
595
+ )
596
+ x_cur += seg_w
597
+
598
+ # Optional trend summary footer pill
599
+ if tr_work is not None:
600
+ t_sub = tr_work[tr_work[resolved_ind].astype(str) == ind]
601
+ t_tot = len(t_sub)
602
+ if t_tot > 0:
603
+ n_imp = int((t_sub["_tr_3"] == "Improving").sum())
604
+ n_deg = int((t_sub["_tr_3"] == "Degrading").sum())
605
+ p_imp = 100.0 * n_imp / t_tot
606
+ p_deg = 100.0 * n_deg / t_tot
607
+ ax.text(
608
+ 0.08,
609
+ 0.16,
610
+ f"↗ {p_imp:.0f}% improving",
611
+ ha="left",
612
+ va="center",
613
+ fontsize=cfg.theme.caption_size - 0.5,
614
+ fontweight="bold",
615
+ color=tr_pal.get("Improving", "#29b6f6"),
616
+ )
617
+ ax.text(
618
+ 0.92,
619
+ 0.16,
620
+ f"↘ {p_deg:.0f}% degrading",
621
+ ha="right",
622
+ va="center",
623
+ fontsize=cfg.theme.caption_size - 0.5,
624
+ fontweight="bold",
625
+ color=tr_pal.get("Degrading", "#ff6666"),
626
+ )
627
+
628
+ fig.subplots_adjust(left=0.03, right=0.97, top=0.96, bottom=0.04)
629
+
630
+ return fig, card_axes
631
+
632
+
633
+ def waffle_infographic(
634
+ counts: dict[str, int | float],
635
+ *,
636
+ rows: int = 10,
637
+ cols: int = 10,
638
+ palette_key: str = "state_bands",
639
+ palette: dict[str, str] | None = None,
640
+ headline_value: str | None = None,
641
+ headline_label: str | None = None,
642
+ title: str | None = None,
643
+ subtitle: str | None = None,
644
+ figsize: tuple[float, float] | None = None,
645
+ ax: Axes | None = None,
646
+ config: str | Path | Config | None = None,
647
+ ) -> tuple[Figure, Axes]:
648
+ """Plot a 10×10 rounded-tile waffle infographic for intuitive proportion storytelling.
649
+
650
+ Args:
651
+ counts: Mapping of ``{category: count_or_pct}`` (automatically scaled to ``rows * cols``).
652
+ rows: Number of tile rows (default ``10``).
653
+ cols: Number of tile columns (default ``10``).
654
+ palette_key: Palette key in ``config.palettes`` (default ``"state_bands"``).
655
+ palette: Optional explicit category-to-hex color mapping override.
656
+ headline_value: Optional large callout stat displayed to the right (e.g., ``"73%"``).
657
+ headline_label: Optional caption below ``headline_value``.
658
+ title: Optional infographic title.
659
+ subtitle: Optional subtitle.
660
+ figsize: Optional ``(width, height)`` override when ``ax`` is None.
661
+ ax: Optional existing Matplotlib ``Axes`` to draw onto.
662
+ config: Optional Config object, preset name, or path to YAML/TOML config.
663
+
664
+ Returns:
665
+ Tuple of ``(fig, ax)``.
666
+ """
667
+ cfg = ensure_config(config)
668
+ resolved_pal = (
669
+ dict(palette)
670
+ if palette is not None
671
+ else cfg.palettes.get(palette_key, resolve_palette(None, cfg, "state_bands"))
672
+ )
673
+
674
+ total_cells = rows * cols
675
+ total_val = float(sum(counts.values()))
676
+ if total_val <= 0:
677
+ raise ValueError("waffle_infographic: Sum of 'counts' must be positive.")
678
+
679
+ # Largest-remainder allocation so tiles sum exactly to rows * cols
680
+ raw_alloc = {k: (v / total_val) * total_cells for k, v in counts.items()}
681
+ floored = {k: int(math.floor(v)) for k, v in raw_alloc.items()}
682
+ remainder = total_cells - sum(floored.values())
683
+ for k in sorted(raw_alloc, key=lambda key: raw_alloc[key] - floored[key], reverse=True)[
684
+ :remainder
685
+ ]:
686
+ floored[k] += 1
687
+
688
+ cell_categories: list[str] = []
689
+ for k, n_tiles in floored.items():
690
+ cell_categories.extend([k] * n_tiles)
691
+
692
+ with mpl_theme(cfg):
693
+ if ax is None:
694
+ fig_w = 9.0 if headline_value else 6.8
695
+ fig, ax = plt.subplots(figsize=figsize or (fig_w, 5.4))
696
+ else:
697
+ fig = ax.figure # type: ignore[assignment]
698
+
699
+ ax.set_facecolor(cfg.theme.background_color)
700
+ for idx, cat in enumerate(cell_categories):
701
+ r_idx = idx // cols
702
+ c_idx = idx % cols
703
+ tile = FancyBboxPatch(
704
+ (c_idx + 0.08, rows - 1 - r_idx + 0.08),
705
+ 0.84,
706
+ 0.84,
707
+ boxstyle="round,pad=0.02,rounding_size=0.16",
708
+ facecolor=resolved_pal.get(cat, "#bdbdbd"),
709
+ edgecolor="none",
710
+ )
711
+ ax.add_patch(tile)
712
+
713
+ x_right = cols + (5.2 if headline_value else 3.2)
714
+ ax.set_xlim(-0.2, x_right)
715
+ ax.set_ylim(-0.4, rows + 0.4)
716
+ ax.set_aspect("equal")
717
+ ax.axis("off")
718
+
719
+ if headline_value:
720
+ ax.text(
721
+ cols + 0.8,
722
+ rows * 0.78,
723
+ headline_value,
724
+ ha="left",
725
+ va="center",
726
+ fontsize=34,
727
+ fontweight="bold",
728
+ color=cfg.theme.text_color,
729
+ )
730
+ if headline_label:
731
+ ax.text(
732
+ cols + 0.8,
733
+ rows * 0.60,
734
+ "\n".join(textwrap.wrap(headline_label, width=22)),
735
+ ha="left",
736
+ va="top",
737
+ fontsize=cfg.theme.label_size,
738
+ color=cfg.theme.caption_color,
739
+ )
740
+
741
+ # Clean vertical legend on right
742
+ leg_y = rows * (0.38 if headline_value else 0.85)
743
+ for idx, (cat, _n_tiles) in enumerate(floored.items()):
744
+ y_pos = leg_y - idx * 0.85
745
+ swatch = FancyBboxPatch(
746
+ (cols + 0.8, y_pos - 0.22),
747
+ 0.45,
748
+ 0.45,
749
+ boxstyle="round,pad=0.01,rounding_size=0.1",
750
+ facecolor=resolved_pal.get(cat, "#bdbdbd"),
751
+ edgecolor="none",
752
+ )
753
+ ax.add_patch(swatch)
754
+ pct = 100.0 * counts[cat] / total_val
755
+ ax.text(
756
+ cols + 1.45,
757
+ y_pos,
758
+ f"{cat} ({pct:.0f}%)",
759
+ ha="left",
760
+ va="center",
761
+ fontsize=cfg.theme.legend_size,
762
+ color=cfg.theme.text_color,
763
+ )
764
+
765
+ if title:
766
+ ax.set_title(
767
+ title if not subtitle else f"{title}\n{subtitle}",
768
+ fontsize=cfg.theme.title_size,
769
+ fontweight=cfg.theme.title_weight,
770
+ color=cfg.theme.text_color,
771
+ loc="left",
772
+ pad=12,
773
+ )
774
+
775
+ return fig, ax
776
+
777
+
778
+ def target_gauge_strip(
779
+ items: list[dict[str, Any]],
780
+ *,
781
+ target_pct: float = 80.0,
782
+ pass_color: str | None = None,
783
+ warn_color: str = "#ffa726",
784
+ fail_color: str = "#ff6666",
785
+ title: str | None = None,
786
+ subtitle: str | None = None,
787
+ figsize: tuple[float, float] | None = None,
788
+ config: str | Path | Config | None = None,
789
+ ) -> tuple[Figure, list[Axes]]:
790
+ """Plot a horizontal strip of 180° semi-circular target-progress gauges.
791
+
792
+ Args:
793
+ items: List of dicts, each with ``"label"`` (str), ``"value"`` (0–100 float),
794
+ and optional ``"target"`` (float, defaults to ``target_pct``) and ``"color"``.
795
+ target_pct: Default target threshold (0–100) shown as a dark benchmark tick.
796
+ pass_color: Arc color when ``value >= target`` (defaults to ``config.theme.accent_color``).
797
+ warn_color: Arc color when ``value >= target * 0.7``.
798
+ fail_color: Arc color when ``value < target * 0.7``.
799
+ title: Optional heading above the gauge strip.
800
+ subtitle: Optional subtitle.
801
+ figsize: Optional ``(width, height)`` override.
802
+ config: Optional Config object, preset name, or path to YAML/TOML config.
803
+
804
+ Returns:
805
+ Tuple of ``(fig, axes_list)``.
806
+ """
807
+ if not items:
808
+ raise ValueError("target_gauge_strip: 'items' must contain at least one gauge dict.")
809
+
810
+ cfg = ensure_config(config)
811
+ n = len(items)
812
+ resolved_pass = pass_color or cfg.theme.accent_color
813
+
814
+ with mpl_theme(cfg):
815
+ fig_size = figsize or (2.9 * n, 3.1 if title else 2.6)
816
+ fig, axes_raw = plt.subplots(1, n, figsize=fig_size)
817
+ fig.patch.set_facecolor(cfg.theme.background_color)
818
+ axes_list: list[Axes] = list(np.asarray(axes_raw).ravel()) if n > 1 else [axes_raw] # type: ignore[list-item]
819
+
820
+ for ax, item in zip(axes_list, items, strict=True):
821
+ val = float(np.clip(item["value"], 0.0, 100.0))
822
+ tgt = float(item.get("target", target_pct))
823
+ if item.get("color"):
824
+ arc_color = str(item["color"])
825
+ elif val >= tgt:
826
+ arc_color = resolved_pass
827
+ elif val >= tgt * 0.7:
828
+ arc_color = warn_color
829
+ else:
830
+ arc_color = fail_color
831
+
832
+ # Track background (180° to 0°)
833
+ bg_arc = Wedge((0, 0), 1.0, 0, 180, width=0.28, facecolor="#e6eaee", edgecolor="none")
834
+ ax.add_patch(bg_arc)
835
+
836
+ # Value arc (starts from left = 180° sweeping clockwise)
837
+ end_angle = 180.0 - (val / 100.0) * 180.0
838
+ if val > 0:
839
+ val_arc = Wedge(
840
+ (0, 0), 1.0, end_angle, 180.0, width=0.28, facecolor=arc_color, edgecolor="none"
841
+ )
842
+ ax.add_patch(val_arc)
843
+
844
+ # Target benchmark tick line
845
+ tgt_angle = math.radians(180.0 - (tgt / 100.0) * 180.0)
846
+ ax.plot(
847
+ [0.68 * math.cos(tgt_angle), 1.06 * math.cos(tgt_angle)],
848
+ [0.68 * math.sin(tgt_angle), 1.06 * math.sin(tgt_angle)],
849
+ color="#1e2a38",
850
+ linewidth=2.2,
851
+ zorder=5,
852
+ )
853
+
854
+ ax.text(
855
+ 0,
856
+ 0.22,
857
+ f"{val:.0f}%",
858
+ ha="center",
859
+ va="center",
860
+ fontsize=20,
861
+ fontweight="bold",
862
+ color=cfg.theme.text_color,
863
+ )
864
+ ax.text(
865
+ 0,
866
+ -0.02,
867
+ f"Target: {tgt:.0f}%",
868
+ ha="center",
869
+ va="center",
870
+ fontsize=cfg.theme.caption_size - 0.5,
871
+ color=cfg.theme.caption_color,
872
+ )
873
+ ax.text(
874
+ 0,
875
+ -0.30,
876
+ "\n".join(textwrap.wrap(resolve_label(str(item["label"]), cfg), width=18)),
877
+ ha="center",
878
+ va="top",
879
+ fontsize=cfg.theme.label_size - 0.5,
880
+ fontweight="bold",
881
+ color=cfg.theme.text_color,
882
+ )
883
+
884
+ ax.set_xlim(-1.18, 1.18)
885
+ ax.set_ylim(-0.62, 1.15)
886
+ ax.set_aspect("equal")
887
+ ax.axis("off")
888
+
889
+ if title:
890
+ fig.suptitle(
891
+ title,
892
+ fontsize=cfg.theme.title_size,
893
+ fontweight=cfg.theme.title_weight,
894
+ color=cfg.theme.text_color,
895
+ y=0.98,
896
+ )
897
+ if subtitle:
898
+ fig.text(
899
+ 0.5,
900
+ 0.89,
901
+ subtitle,
902
+ ha="center",
903
+ va="top",
904
+ fontsize=cfg.theme.subtitle_size,
905
+ color=cfg.theme.caption_color,
906
+ )
907
+ fig.tight_layout(rect=(0.0, 0.0, 1.0, 0.86 if title else 1.0))
908
+
909
+ return fig, axes_list
910
+
911
+
912
+ def regional_infographic_poster(
913
+ *,
914
+ title: str,
915
+ subtitle: str,
916
+ kpis: list[dict[str, Any]],
917
+ fmu_polygons: Any,
918
+ waffle_counts: dict[str, int | float],
919
+ takeaways: list[str],
920
+ context_polygons: Any = None,
921
+ rivers: Any = None,
922
+ towns: pd.DataFrame | None = None,
923
+ sites_df: pd.DataFrame | None = None,
924
+ fmu_name_col: str | None = None,
925
+ highlight_fmu: str | None = None,
926
+ waffle_title: str = "Regional State Grade Breakdown",
927
+ waffle_headline: str | None = None,
928
+ waffle_label: str | None = None,
929
+ footer: str = "Generated with stplot",
930
+ config: str | Path | Config | None = None,
931
+ ) -> tuple[Figure, dict[str, Axes]]:
932
+ """Assemble a vertical A4 1-page Regional 'At-a-Glance' Infographic Poster.
933
+
934
+ Combines a branded top banner, KPI strip, editorial FMU map, 10×10 waffle breakdown,
935
+ and a Key Takeaways callout box into a single exportable A4 figure.
936
+
937
+ Returns:
938
+ Tuple of ``(fig, axes_dict)``.
939
+ """
940
+ cfg = ensure_config(config)
941
+ a4_size = cfg.figure_sizes.get("a4_poster", (8.27, 11.69))
942
+
943
+ with mpl_theme(cfg):
944
+ fig = plt.figure(figsize=(a4_size[0] * 1.15, a4_size[1] * 1.15))
945
+ fig.patch.set_facecolor(cfg.theme.background_color)
946
+
947
+ gs = GridSpec(
948
+ 4,
949
+ 2,
950
+ figure=fig,
951
+ height_ratios=[0.55, 0.65, 2.35, 0.85],
952
+ width_ratios=[1.15, 1.0],
953
+ hspace=0.22,
954
+ wspace=0.14,
955
+ )
956
+
957
+ # Row 0: Branded Title Banner
958
+ ax_banner = fig.add_subplot(gs[0, :])
959
+ ax_banner.set_xlim(0, 1)
960
+ ax_banner.set_ylim(0, 1)
961
+ ax_banner.axis("off")
962
+ banner = FancyBboxPatch(
963
+ (0.0, 0.05),
964
+ 1.0,
965
+ 0.90,
966
+ boxstyle="round,pad=0.01,rounding_size=0.04",
967
+ facecolor="#263742",
968
+ edgecolor="none",
969
+ )
970
+ ax_banner.add_patch(banner)
971
+ ax_banner.text(
972
+ 0.03,
973
+ 0.64,
974
+ title,
975
+ ha="left",
976
+ va="center",
977
+ fontsize=18,
978
+ fontweight="bold",
979
+ color="#ffffff",
980
+ )
981
+ ax_banner.text(
982
+ 0.03,
983
+ 0.25,
984
+ subtitle,
985
+ ha="left",
986
+ va="center",
987
+ fontsize=11,
988
+ color="#cfd8dc",
989
+ )
990
+
991
+ # Row 1: KPI Strip
992
+ ax_kpi = fig.add_subplot(gs[1, :])
993
+ ax_kpi.set_xlim(0, len(kpis))
994
+ ax_kpi.set_ylim(0, 1)
995
+ ax_kpi.axis("off")
996
+ for idx, card in enumerate(kpis):
997
+ accent = str(card.get("color") or cfg.theme.accent_color)
998
+ box = FancyBboxPatch(
999
+ (idx + 0.04, 0.05),
1000
+ 0.92,
1001
+ 0.90,
1002
+ boxstyle="round,pad=0.01,rounding_size=0.05",
1003
+ facecolor="#f8fafc",
1004
+ edgecolor=cfg.theme.spine_color,
1005
+ linewidth=1.0,
1006
+ )
1007
+ ax_kpi.add_patch(box)
1008
+ top = FancyBboxPatch(
1009
+ (idx + 0.04, 0.85),
1010
+ 0.92,
1011
+ 0.10,
1012
+ boxstyle="round,pad=0.01,rounding_size=0.03",
1013
+ facecolor=accent,
1014
+ edgecolor="none",
1015
+ )
1016
+ ax_kpi.add_patch(top)
1017
+ ax_kpi.text(
1018
+ idx + 0.5,
1019
+ 0.56,
1020
+ str(card["value"]),
1021
+ ha="center",
1022
+ va="center",
1023
+ fontsize=20,
1024
+ fontweight="bold",
1025
+ color=cfg.theme.text_color,
1026
+ )
1027
+ ax_kpi.text(
1028
+ idx + 0.5,
1029
+ 0.24,
1030
+ str(card["label"]),
1031
+ ha="center",
1032
+ va="center",
1033
+ fontsize=9.5,
1034
+ fontweight="bold",
1035
+ color=cfg.theme.caption_color,
1036
+ )
1037
+
1038
+ # Row 2 Left: Editorial Map
1039
+ ax_map = fig.add_subplot(gs[2, 0])
1040
+ publication_map(
1041
+ fmu_polygons,
1042
+ context_polygons=context_polygons,
1043
+ rivers=rivers,
1044
+ towns=towns,
1045
+ sites_df=sites_df,
1046
+ fmu_name_col=fmu_name_col,
1047
+ highlight_fmu=highlight_fmu,
1048
+ title="Regional Monitoring Network",
1049
+ ax=ax_map,
1050
+ config=cfg,
1051
+ )
1052
+
1053
+ # Row 2 Right: Waffle Infographic
1054
+ ax_waffle = fig.add_subplot(gs[2, 1])
1055
+ waffle_infographic(
1056
+ waffle_counts,
1057
+ headline_value=waffle_headline,
1058
+ headline_label=waffle_label,
1059
+ title=waffle_title,
1060
+ ax=ax_waffle,
1061
+ config=cfg,
1062
+ )
1063
+
1064
+ # Row 3: Key Takeaways Box
1065
+ ax_notes = fig.add_subplot(gs[3, :])
1066
+ ax_notes.set_xlim(0, 1)
1067
+ ax_notes.set_ylim(0, 1)
1068
+ ax_notes.axis("off")
1069
+ notes_box = FancyBboxPatch(
1070
+ (0.0, 0.08),
1071
+ 1.0,
1072
+ 0.88,
1073
+ boxstyle="round,pad=0.01,rounding_size=0.04",
1074
+ facecolor="#f3f5f7",
1075
+ edgecolor=cfg.theme.spine_color,
1076
+ linewidth=1.0,
1077
+ )
1078
+ ax_notes.add_patch(notes_box)
1079
+ ax_notes.text(
1080
+ 0.025,
1081
+ 0.82,
1082
+ "Key Takeaways",
1083
+ ha="left",
1084
+ va="center",
1085
+ fontsize=12,
1086
+ fontweight="bold",
1087
+ color="#263742",
1088
+ )
1089
+ y_step = 0.62 / max(len(takeaways), 1)
1090
+ for idx, bullet in enumerate(takeaways):
1091
+ ax_notes.text(
1092
+ 0.035,
1093
+ 0.62 - idx * y_step,
1094
+ f"• {bullet}",
1095
+ ha="left",
1096
+ va="center",
1097
+ fontsize=10,
1098
+ color=cfg.theme.text_color,
1099
+ )
1100
+
1101
+ fig.text(
1102
+ 0.5,
1103
+ 0.012,
1104
+ footer,
1105
+ ha="center",
1106
+ va="bottom",
1107
+ fontsize=8.5,
1108
+ color=cfg.theme.caption_color,
1109
+ )
1110
+ fig.subplots_adjust(left=0.04, right=0.96, top=0.97, bottom=0.04)
1111
+
1112
+ return fig, {
1113
+ "banner": ax_banner,
1114
+ "kpi": ax_kpi,
1115
+ "map": ax_map,
1116
+ "waffle": ax_waffle,
1117
+ "takeaways": ax_notes,
1118
+ }