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,1940 @@
1
+ """Additional infographic templates (flower, stripes, bullet, beeswarm, bump, swim, spotlight)."""
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.patches import Circle, FancyBboxPatch, Polygon, Rectangle
16
+
17
+ from stplot.config import (
18
+ Config,
19
+ ensure_config,
20
+ resolve_category_order,
21
+ resolve_column,
22
+ resolve_label,
23
+ resolve_palette,
24
+ )
25
+ from stplot.theme.mpl import mpl_theme, style_axes
26
+ from stplot.transform.columns import validate_columns
27
+
28
+
29
+ def _contrast_text(hex_color: str) -> str:
30
+ cleaned = str(hex_color).lstrip("#")
31
+ if len(cleaned) != 6:
32
+ return "#1e2a38"
33
+ r, g, b = int(cleaned[0:2], 16), int(cleaned[2:4], 16), int(cleaned[4:6], 16)
34
+ return "#111111" if (0.299 * r + 0.587 * g + 0.114 * b) > 150 else "#ffffff"
35
+
36
+
37
+ def _default_pass_set() -> set[str]:
38
+ return {"A", "B", "PASS", "TRUE", "1", "SUITABLE", "GREEN"}
39
+
40
+
41
+ def ecosystem_flower_plot(
42
+ df: pd.DataFrame,
43
+ *,
44
+ indicator_col: str | None = None,
45
+ score_col: str | None = None,
46
+ grade_col: str | None = None,
47
+ weight_col: str | None = None,
48
+ pass_values: tuple[Any, ...] | list[Any] | None = None,
49
+ center_label: str | None = None,
50
+ center_sublabel: str = "Overall",
51
+ center_color: str | None = None,
52
+ palette: dict[str, str] | None = None,
53
+ palette_name: str = "state_bands",
54
+ title: str = "Ecosystem Health Flower",
55
+ subtitle: str | None = None,
56
+ ring_ticks: tuple[int, ...] = (25, 50, 75, 100),
57
+ figsize: tuple[float, float] | None = None,
58
+ ax: Axes | None = None,
59
+ config: str | Path | Config | None = None,
60
+ ) -> tuple[Figure, Axes]:
61
+ """Render an Ocean Health Index / Waterway Report Card style flower (petal) plot.
62
+
63
+ Each radial petal represents one environmental indicator. Petal length encodes the
64
+ indicator score (0–100, e.g., ``% Band A/B`` or ``% Passing One Plan``), petal color
65
+ encodes the indicator grade (or score band), and optional ``weight_col`` scales each
66
+ petal's angular width.
67
+
68
+ Accepts either:
69
+ - Pre-summarized data with one row per indicator (provide ``score_col`` and
70
+ optionally ``grade_col`` / ``weight_col``), OR
71
+ - Site-level rows (omit ``score_col`` and provide ``grade_col`` / default
72
+ ``state_band``), in which case ``%`` of sites in ``pass_values`` is computed
73
+ automatically per indicator.
74
+
75
+ Returns:
76
+ Tuple of ``(fig, ax)``.
77
+ """
78
+ cfg = ensure_config(config)
79
+ resolved_ind = resolve_column(indicator_col, cfg, "indicator")
80
+ resolved_grade = resolve_column(grade_col, cfg, "state_band")
81
+ resolved_pal = resolve_palette(palette, cfg, palette_name)
82
+
83
+ if len(df) == 0:
84
+ raise ValueError("ecosystem_flower_plot: Input DataFrame is empty.")
85
+
86
+ work = df.copy()
87
+ if score_col is not None:
88
+ validate_columns(work, [resolved_ind, score_col], context="ecosystem_flower_plot")
89
+ summary = work.copy()
90
+ summary["_score"] = pd.to_numeric(summary[score_col], errors="coerce").clip(0, 100)
91
+ if resolved_grade in summary.columns:
92
+ summary["_grade"] = summary[resolved_grade].astype(str)
93
+ else:
94
+ summary["_grade"] = summary["_score"].apply(
95
+ lambda v: (
96
+ "A"
97
+ if v >= 80
98
+ else ("B" if v >= 60 else ("C" if v >= 40 else ("D" if v >= 20 else "E")))
99
+ )
100
+ )
101
+ if weight_col and weight_col in summary.columns:
102
+ summary["_weight"] = (
103
+ pd.to_numeric(summary[weight_col], errors="coerce").fillna(1.0).clip(lower=0.1)
104
+ )
105
+ else:
106
+ summary["_weight"] = 1.0
107
+ else:
108
+ validate_columns(work, [resolved_ind, resolved_grade], context="ecosystem_flower_plot")
109
+ pass_set = (
110
+ {str(v).strip().upper() for v in pass_values}
111
+ if pass_values is not None
112
+ else _default_pass_set()
113
+ )
114
+ rows = []
115
+ for ind, grp in work.groupby(resolved_ind, sort=False):
116
+ vals = grp[resolved_grade].dropna()
117
+ n_ok = len(vals)
118
+ pct = (
119
+ 100.0 * vals.astype(str).str.strip().str.upper().isin(pass_set).mean()
120
+ if n_ok > 0
121
+ else 0.0
122
+ )
123
+ mode_grade = str(vals.mode().iloc[0]) if n_ok > 0 else "Not assessed"
124
+ rows.append(
125
+ {
126
+ resolved_ind: ind,
127
+ "_score": pct,
128
+ "_grade": mode_grade,
129
+ "_weight": float(max(n_ok, 1)),
130
+ }
131
+ )
132
+ summary = pd.DataFrame(rows)
133
+
134
+ summary = summary.dropna(subset=["_score"]).reset_index(drop=True)
135
+ if summary.empty:
136
+ raise ValueError("ecosystem_flower_plot: No valid numeric scores to plot.")
137
+
138
+ n = len(summary)
139
+ weights = summary["_weight"].to_numpy(dtype=float)
140
+ total_w = float(weights.sum())
141
+ # Start at 12 o'clock (pi/2) and proceed clockwise
142
+ angles_span = 2.0 * np.pi * (weights / total_w)
143
+
144
+ r_inner = 0.27
145
+ r_max = 0.94
146
+
147
+ overall_score = float(np.average(summary["_score"], weights=weights))
148
+ resolved_center_label = center_label if center_label is not None else f"{overall_score:.0f}%"
149
+ if center_color is None:
150
+ if resolved_center_label in resolved_pal:
151
+ center_color = resolved_pal[resolved_center_label]
152
+ else:
153
+ auto_grade = (
154
+ "A"
155
+ if overall_score >= 80
156
+ else (
157
+ "B"
158
+ if overall_score >= 60
159
+ else ("C" if overall_score >= 40 else ("D" if overall_score >= 20 else "E"))
160
+ )
161
+ )
162
+ center_color = resolved_pal.get(auto_grade, cfg.theme.accent_color)
163
+
164
+ with mpl_theme(cfg):
165
+ if ax is None:
166
+ fig, ax = plt.subplots(figsize=figsize or (7.8, 7.6))
167
+ else:
168
+ fig = ax.figure # type: ignore[assignment]
169
+
170
+ ax.set_facecolor(cfg.theme.background_color)
171
+ ax.set_aspect("equal")
172
+
173
+ # Concentric reference rings
174
+ for tick in ring_ticks:
175
+ r_ring = r_inner + (r_max - r_inner) * (tick / 100.0)
176
+ circle = Circle(
177
+ (0, 0),
178
+ r_ring,
179
+ facecolor="none",
180
+ edgecolor=cfg.theme.grid_color,
181
+ linewidth=0.9 if tick < 100 else 1.2,
182
+ linestyle="--" if tick < 100 else "-",
183
+ zorder=1,
184
+ )
185
+ ax.add_patch(circle)
186
+ ax.text(
187
+ 0.0,
188
+ r_ring,
189
+ f"{tick}%",
190
+ fontsize=cfg.theme.caption_size - 1.5,
191
+ color=cfg.theme.caption_color,
192
+ ha="center",
193
+ va="center",
194
+ bbox={
195
+ "boxstyle": "round,pad=0.12",
196
+ "facecolor": "#ffffff",
197
+ "edgecolor": "none",
198
+ "alpha": 0.85,
199
+ },
200
+ zorder=6,
201
+ )
202
+
203
+ # Draw each petal as a smooth curved wedge with slight gap
204
+ theta_curr = np.pi / 2.0
205
+ gap = min(0.045, 0.16 * (2.0 * np.pi / max(n, 1)))
206
+
207
+ for i, row in summary.iterrows():
208
+ span = float(angles_span[i])
209
+ t0 = theta_curr - gap / 2.0
210
+ t1 = theta_curr - span + gap / 2.0
211
+ t_mid = (t0 + t1) / 2.0
212
+ theta_curr -= span
213
+
214
+ score = float(row["_score"])
215
+ grade = str(row["_grade"])
216
+ r_outer = r_inner + (r_max - r_inner) * (score / 100.0)
217
+ color = resolved_pal.get(grade, cfg.theme.accent_color)
218
+
219
+ # Soft background guide wedge to 100%
220
+ arc_full = np.linspace(t0, t1, 28)
221
+ bg_pts = np.vstack(
222
+ [
223
+ np.column_stack([r_inner * np.cos(arc_full), r_inner * np.sin(arc_full)]),
224
+ np.column_stack(
225
+ [r_max * np.cos(arc_full[::-1]), r_max * np.sin(arc_full[::-1])]
226
+ ),
227
+ ]
228
+ )
229
+ ax.add_patch(
230
+ Polygon(
231
+ bg_pts,
232
+ closed=True,
233
+ facecolor="#f4f6f9",
234
+ edgecolor="none",
235
+ alpha=0.55,
236
+ zorder=1,
237
+ )
238
+ )
239
+
240
+ # Actual petal with gently rounded outer arc
241
+ arc_in = np.linspace(t0, t1, 24)
242
+ arc_out = np.linspace(t1, t0, 36)
243
+ # Taper slightly at edges for organic petal look
244
+ taper = 1.0 - 0.03 * ((arc_out - t_mid) / max(abs(t0 - t1) / 2.0, 1e-6)) ** 2
245
+ r_curve = np.maximum(r_inner + 0.02, r_outer * taper)
246
+
247
+ petal_pts = np.vstack(
248
+ [
249
+ np.column_stack([r_inner * np.cos(arc_in), r_inner * np.sin(arc_in)]),
250
+ np.column_stack([r_curve * np.cos(arc_out), r_curve * np.sin(arc_out)]),
251
+ ]
252
+ )
253
+ ax.add_patch(
254
+ Polygon(
255
+ petal_pts,
256
+ closed=True,
257
+ facecolor=color,
258
+ edgecolor="#ffffff",
259
+ linewidth=1.5,
260
+ alpha=0.92,
261
+ zorder=3,
262
+ )
263
+ )
264
+
265
+ # Outer indicator label + score
266
+ r_label = r_max + 0.11
267
+ lx = r_label * np.cos(t_mid)
268
+ ly = r_label * np.sin(t_mid)
269
+ cos_m = np.cos(t_mid)
270
+ if abs(cos_m) < 0.18:
271
+ ha = "center"
272
+ elif cos_m > 0:
273
+ ha = "left"
274
+ else:
275
+ ha = "right"
276
+ va = (
277
+ "center"
278
+ if abs(np.sin(t_mid)) < 0.85
279
+ else ("bottom" if np.sin(t_mid) > 0 else "top")
280
+ )
281
+
282
+ ind_name = resolve_label(str(row[resolved_ind]), cfg)
283
+ ind_short = textwrap.fill(ind_name, width=18)
284
+ ax.text(
285
+ lx,
286
+ ly,
287
+ f"{ind_short}\n{score:.0f}% ({grade})",
288
+ ha=ha,
289
+ va=va,
290
+ fontsize=cfg.theme.tick_size,
291
+ fontweight="bold",
292
+ color=cfg.theme.text_color,
293
+ linespacing=1.18,
294
+ zorder=6,
295
+ )
296
+
297
+ # Center halo + overall grade/score badge
298
+ ax.add_patch(
299
+ Circle((0, 0), r_inner + 0.015, facecolor="#ffffff", edgecolor="none", zorder=4)
300
+ )
301
+ ax.add_patch(
302
+ Circle(
303
+ (0, 0),
304
+ r_inner - 0.01,
305
+ facecolor=center_color,
306
+ edgecolor="#ffffff",
307
+ linewidth=2.0,
308
+ zorder=5,
309
+ )
310
+ )
311
+ c_txt = _contrast_text(center_color)
312
+ ax.text(
313
+ 0,
314
+ 0.035,
315
+ resolved_center_label,
316
+ ha="center",
317
+ va="center",
318
+ fontsize=cfg.theme.title_size + 5,
319
+ fontweight="bold",
320
+ color=c_txt,
321
+ zorder=6,
322
+ )
323
+ ax.text(
324
+ 0,
325
+ -0.11,
326
+ center_sublabel,
327
+ ha="center",
328
+ va="center",
329
+ fontsize=cfg.theme.caption_size,
330
+ color=c_txt,
331
+ alpha=0.92,
332
+ zorder=6,
333
+ )
334
+
335
+ ax.set_xlim(-1.46, 1.46)
336
+ ax.set_ylim(-1.38, 1.38)
337
+ ax.axis("off")
338
+
339
+ fig.suptitle(
340
+ title,
341
+ fontsize=cfg.theme.title_size + 1,
342
+ fontweight=cfg.theme.title_weight,
343
+ color=cfg.theme.text_color,
344
+ y=0.97,
345
+ )
346
+ if subtitle:
347
+ fig.text(
348
+ 0.5,
349
+ 0.925,
350
+ subtitle,
351
+ ha="center",
352
+ va="top",
353
+ fontsize=cfg.theme.subtitle_size,
354
+ color=cfg.theme.caption_color,
355
+ )
356
+
357
+ return fig, ax
358
+
359
+
360
+ def water_quality_stripes(
361
+ df: pd.DataFrame,
362
+ *,
363
+ period_col: str | None = None,
364
+ band_col: str | None = None,
365
+ entity_col: str | None = None,
366
+ period_order: list[str] | None = None,
367
+ entity_order: list[str] | None = None,
368
+ palette: dict[str, str] | None = None,
369
+ palette_name: str = "state_bands",
370
+ minimal: bool = False,
371
+ show_legend: bool = True,
372
+ title: str = "Water Quality Stripes",
373
+ subtitle: str | None = None,
374
+ figsize: tuple[float, float] | None = None,
375
+ ax: Axes | None = None,
376
+ config: str | Path | Config | None = None,
377
+ ) -> tuple[Figure, Axes]:
378
+ """Render #ShowYourStripes-inspired chronological water quality stripes.
379
+
380
+ Each vertical stripe represents one monitoring period (e.g., rolling 5-year window or
381
+ year), colored by NPS-FM NOF Grade or One Plan Pass/Fail. Supply ``entity_col`` to
382
+ stack multiple sites or FMUs as sleek horizontal ribbons, or omit it for a single
383
+ full-bleed poster strip.
384
+
385
+ Returns:
386
+ Tuple of ``(fig, ax)``.
387
+ """
388
+ cfg = ensure_config(config)
389
+ resolved_period = resolve_column(period_col, cfg, "period")
390
+ resolved_band = resolve_column(band_col, cfg, "state_band")
391
+ req = [resolved_period, resolved_band]
392
+ if entity_col is not None:
393
+ req.append(entity_col)
394
+ validate_columns(df, req, context="water_quality_stripes")
395
+
396
+ if len(df) == 0:
397
+ raise ValueError("water_quality_stripes: Input DataFrame is empty.")
398
+
399
+ work = df.copy()
400
+ if entity_col is None:
401
+ work["_entity"] = ""
402
+ entities = [""]
403
+ else:
404
+ work["_entity"] = work[entity_col].astype(str)
405
+ entities = (
406
+ entity_order if entity_order is not None else list(dict.fromkeys(work["_entity"]))
407
+ )
408
+
409
+ periods = (
410
+ period_order
411
+ if period_order is not None
412
+ else sorted(work[resolved_period].dropna().astype(str).unique().tolist())
413
+ )
414
+ if not periods:
415
+ raise ValueError("water_quality_stripes: No valid period values found.")
416
+
417
+ resolved_pal = resolve_palette(palette, cfg, palette_name)
418
+ pivot = (
419
+ work.assign(_p=work[resolved_period].astype(str))
420
+ .pivot_table(index="_entity", columns="_p", values=resolved_band, aggfunc="first")
421
+ .reindex(index=entities, columns=periods)
422
+ )
423
+
424
+ n_rows = len(entities)
425
+ n_cols = len(periods)
426
+
427
+ with mpl_theme(cfg):
428
+ if ax is None:
429
+ fig_h = max(2.6, 0.62 * n_rows + (1.2 if minimal else 2.2))
430
+ fig, ax = plt.subplots(figsize=figsize or (11.0, fig_h))
431
+ else:
432
+ fig = ax.figure # type: ignore[assignment]
433
+
434
+ ax.set_facecolor(cfg.theme.background_color)
435
+ row_gap = 0.22 if n_rows > 1 else 0.0
436
+ row_h = 1.0 - row_gap
437
+
438
+ present_cats: list[str] = []
439
+ for r_idx, ent in enumerate(entities):
440
+ y_base = (n_rows - 1 - r_idx) + row_gap / 2.0
441
+ for c_idx, per in enumerate(periods):
442
+ val = pivot.loc[ent, per]
443
+ cat = "Not assessed" if pd.isna(val) else str(val)
444
+ if cat not in present_cats:
445
+ present_cats.append(cat)
446
+ color = resolved_pal.get(cat, "#d9dee6")
447
+ ax.add_patch(
448
+ Rectangle(
449
+ (c_idx, y_base),
450
+ 1.0,
451
+ row_h,
452
+ facecolor=color,
453
+ edgecolor="none",
454
+ zorder=2,
455
+ )
456
+ )
457
+
458
+ if not minimal and entity_col is not None:
459
+ ax.text(
460
+ -0.18,
461
+ y_base + row_h / 2.0,
462
+ ent,
463
+ ha="right",
464
+ va="center",
465
+ fontsize=cfg.theme.tick_size,
466
+ fontweight="bold",
467
+ color=cfg.theme.text_color,
468
+ )
469
+
470
+ ax.set_xlim(0, n_cols)
471
+ ax.set_ylim(0, n_rows)
472
+
473
+ if minimal:
474
+ ax.axis("off")
475
+ else:
476
+ ax.set_yticks([])
477
+ step = max(1, math.ceil(n_cols / 10))
478
+ tick_idx = list(range(0, n_cols, step))
479
+ if (n_cols - 1) not in tick_idx:
480
+ tick_idx.append(n_cols - 1)
481
+ ax.set_xticks([i + 0.5 for i in tick_idx])
482
+ ax.set_xticklabels(
483
+ [periods[i] for i in tick_idx],
484
+ fontsize=cfg.theme.tick_size - 0.5,
485
+ color=cfg.theme.text_color,
486
+ )
487
+ ax.tick_params(axis="x", length=0, pad=6)
488
+ for spine in ax.spines.values():
489
+ spine.set_visible(False)
490
+
491
+ if show_legend:
492
+ order = resolve_category_order(None, cfg, palette_name)
493
+ ordered_cats = [c for c in order if c in present_cats] + [
494
+ c for c in present_cats if c not in order
495
+ ]
496
+ handles = [
497
+ Rectangle(
498
+ (0, 0), 1, 1, facecolor=resolved_pal.get(c, "#d9dee6"), edgecolor="none"
499
+ )
500
+ for c in ordered_cats
501
+ ]
502
+ ax.legend(
503
+ handles,
504
+ ordered_cats,
505
+ loc="upper center",
506
+ bbox_to_anchor=(0.5, -0.18 if n_rows <= 2 else -0.12),
507
+ ncol=min(len(ordered_cats), 6),
508
+ frameon=False,
509
+ fontsize=cfg.theme.legend_size,
510
+ )
511
+
512
+ if title and not minimal:
513
+ fig.suptitle(
514
+ title,
515
+ fontsize=cfg.theme.title_size + 1,
516
+ fontweight=cfg.theme.title_weight,
517
+ color=cfg.theme.text_color,
518
+ y=0.98,
519
+ )
520
+ if subtitle:
521
+ fig.text(
522
+ 0.5,
523
+ 0.91 if n_rows <= 2 else 0.93,
524
+ subtitle,
525
+ ha="center",
526
+ va="top",
527
+ fontsize=cfg.theme.subtitle_size,
528
+ color=cfg.theme.caption_color,
529
+ )
530
+ fig.subplots_adjust(
531
+ left=0.22 if entity_col is not None else 0.05,
532
+ right=0.97,
533
+ top=0.83 if subtitle else 0.88,
534
+ bottom=0.20 if show_legend else 0.12,
535
+ )
536
+
537
+ return fig, ax
538
+
539
+
540
+ def bullet_scorecard(
541
+ df: pd.DataFrame,
542
+ *,
543
+ indicator_col: str | None = None,
544
+ value_col: str = "Value",
545
+ target_col: str | None = None,
546
+ target: float | None = 80.0,
547
+ scale_max: float | None = 100.0,
548
+ bands: list[tuple[float, str]] | None = None,
549
+ bar_color: str | None = None,
550
+ target_color: str = "#111827",
551
+ value_fmt: str = "{:.0f}%",
552
+ target_label: str = "Target",
553
+ title: str = "Multi-Metric Bullet Scorecard",
554
+ subtitle: str | None = None,
555
+ xlabel: str = "Score / % Compliance",
556
+ ylabel: str = "",
557
+ figsize: tuple[float, float] | None = None,
558
+ ax: Axes | None = None,
559
+ config: str | Path | Config | None = None,
560
+ ) -> tuple[Figure, Axes]:
561
+ """Render a compact Stephen Few / IBCS-style multi-metric bullet chart scorecard.
562
+
563
+ Each horizontal row shows qualitative shaded background ranges (e.g., Poor / Fair /
564
+ Good / Excellent), a crisp dark actual value bar, a bold vertical target marker
565
+ (e.g., National Bottom Line or One Plan target), and a right-hand gap readout.
566
+
567
+ Returns:
568
+ Tuple of ``(fig, ax)``.
569
+ """
570
+ cfg = ensure_config(config)
571
+ resolved_ind = resolve_column(indicator_col, cfg, "indicator")
572
+ req = [resolved_ind, value_col]
573
+ if target_col is not None:
574
+ req.append(target_col)
575
+ validate_columns(df, req, context="bullet_scorecard")
576
+
577
+ work = df.copy().reset_index(drop=True)
578
+ if work.empty:
579
+ raise ValueError("bullet_scorecard: Input DataFrame is empty.")
580
+
581
+ vals = pd.to_numeric(work[value_col], errors="coerce").fillna(0.0).to_numpy(dtype=float)
582
+ if target_col is not None:
583
+ targets = pd.to_numeric(work[target_col], errors="coerce").to_numpy(dtype=float)
584
+ else:
585
+ targets = np.full(len(work), target if target is not None else np.nan, dtype=float)
586
+
587
+ vmax = (
588
+ float(scale_max)
589
+ if scale_max is not None
590
+ else float(
591
+ max(np.nanmax(vals), np.nanmax(targets) if not np.all(np.isnan(targets)) else 0.0)
592
+ * 1.15
593
+ )
594
+ )
595
+ if vmax <= 0:
596
+ vmax = 100.0
597
+
598
+ # Qualitative background bands: list of (upper_bound, hex_color)
599
+ resolved_bands = bands or [
600
+ (0.40 * vmax, "#e5e9f0"),
601
+ (0.70 * vmax, "#eef2f7"),
602
+ (vmax, "#f7f9fc"),
603
+ ]
604
+ resolved_bands = sorted(resolved_bands, key=lambda b: b[0])
605
+ resolved_bar_color = bar_color or cfg.theme.accent_color
606
+
607
+ n = len(work)
608
+ labels = [resolve_label(str(v), cfg) for v in work[resolved_ind]]
609
+
610
+ with mpl_theme(cfg):
611
+ if ax is None:
612
+ fig_h = max(3.6, 0.58 * n + 1.8)
613
+ fig, ax = plt.subplots(figsize=figsize or (10.5, fig_h))
614
+ else:
615
+ fig = ax.figure # type: ignore[assignment]
616
+
617
+ ys = np.arange(n)[::-1]
618
+ band_h = 0.62
619
+ bar_h = 0.28
620
+
621
+ for idx, y in enumerate(ys):
622
+ # Qualitative background bands
623
+ prev = 0.0
624
+ for upper, b_color in resolved_bands:
625
+ width = max(0.0, upper - prev)
626
+ ax.barh(
627
+ y,
628
+ width,
629
+ left=prev,
630
+ height=band_h,
631
+ color=b_color,
632
+ edgecolor="#d8dfe8",
633
+ linewidth=0.5,
634
+ zorder=1,
635
+ )
636
+ prev = upper
637
+
638
+ # Actual bar
639
+ val = vals[idx]
640
+ tgt = targets[idx]
641
+ meets = (not np.isnan(tgt)) and val >= tgt
642
+ fill = resolved_bar_color if (np.isnan(tgt) or meets) else "#c94c4c"
643
+ ax.barh(y, val, height=bar_h, color=fill, edgecolor="none", zorder=3)
644
+
645
+ # Target marker
646
+ if not np.isnan(tgt):
647
+ ax.plot(
648
+ [tgt, tgt],
649
+ [y - band_h * 0.56, y + band_h * 0.56],
650
+ color=target_color,
651
+ linewidth=2.6,
652
+ solid_capstyle="butt",
653
+ zorder=4,
654
+ )
655
+ diff = val - tgt
656
+ diff_str = (
657
+ f"({diff:+.0f})"
658
+ if value_fmt.endswith("%}") or ".0f" in value_fmt
659
+ else f"({diff:+.2f})"
660
+ )
661
+ diff_color = "#2e7d32" if diff >= 0 else "#c62828"
662
+ ax.text(
663
+ vmax * 1.02,
664
+ y,
665
+ f"{value_fmt.format(val)} ",
666
+ ha="left",
667
+ va="center",
668
+ fontsize=cfg.theme.tick_size,
669
+ fontweight="bold",
670
+ color=cfg.theme.text_color,
671
+ )
672
+ ax.text(
673
+ vmax * 1.11,
674
+ y,
675
+ diff_str,
676
+ ha="left",
677
+ va="center",
678
+ fontsize=cfg.theme.caption_size,
679
+ fontweight="bold",
680
+ color=diff_color,
681
+ )
682
+ else:
683
+ ax.text(
684
+ vmax * 1.02,
685
+ y,
686
+ value_fmt.format(val),
687
+ ha="left",
688
+ va="center",
689
+ fontsize=cfg.theme.tick_size,
690
+ fontweight="bold",
691
+ color=cfg.theme.text_color,
692
+ )
693
+
694
+ ax.set_yticks(ys)
695
+ ax.set_yticklabels(labels, fontsize=cfg.theme.tick_size, fontweight="bold")
696
+ ax.set_xlim(0, vmax * 1.22)
697
+ ax.set_ylim(-0.6, n - 0.35)
698
+ ax.xaxis.grid(True, linestyle=":", color=cfg.theme.grid_color, zorder=0)
699
+ ax.yaxis.grid(False)
700
+
701
+ # Compact legend for actual bar & target marker
702
+ legend_handles = [
703
+ Rectangle((0, 0), 1, 1, facecolor=resolved_bar_color, label="Meets target"),
704
+ Rectangle((0, 0), 1, 1, facecolor="#c94c4c", label="Below target"),
705
+ plt.Line2D([0], [0], color=target_color, linewidth=2.6, label=target_label),
706
+ ]
707
+ ax.legend(
708
+ handles=legend_handles,
709
+ loc="upper right",
710
+ frameon=False,
711
+ ncol=3,
712
+ fontsize=cfg.theme.legend_size - 0.5,
713
+ bbox_to_anchor=(1.0, 1.09),
714
+ )
715
+
716
+ style_axes(ax, title=None, xlabel=xlabel, ylabel=ylabel, config=cfg)
717
+ ax.yaxis.grid(False)
718
+ ax.xaxis.grid(True, linestyle=":", color=cfg.theme.grid_color, zorder=0)
719
+ fig.suptitle(
720
+ title,
721
+ fontsize=cfg.theme.title_size + 1,
722
+ fontweight=cfg.theme.title_weight,
723
+ color=cfg.theme.text_color,
724
+ y=0.98,
725
+ )
726
+ if subtitle:
727
+ fig.text(
728
+ 0.5,
729
+ 0.92,
730
+ subtitle,
731
+ ha="center",
732
+ va="top",
733
+ fontsize=cfg.theme.subtitle_size,
734
+ color=cfg.theme.caption_color,
735
+ )
736
+ fig.tight_layout(rect=(0.0, 0.0, 1.0, 0.87 if subtitle else 0.92))
737
+
738
+ return fig, ax
739
+
740
+
741
+ def _pack_beeswarm(values: np.ndarray, radius_y: float, step_x: float, max_x: float) -> np.ndarray:
742
+ """Deterministic greedy beeswarm x-offset packer (zero external deps)."""
743
+ n = len(values)
744
+ order = np.argsort(values)
745
+ offsets = np.zeros(n, dtype=float)
746
+ placed_x: list[float] = []
747
+ placed_y: list[float] = []
748
+
749
+ candidates = [0.0]
750
+ k = 1
751
+ while k * step_x <= max_x:
752
+ candidates.extend([k * step_x, -k * step_x])
753
+ k += 1
754
+
755
+ for idx in order:
756
+ y = float(values[idx])
757
+ best_x = 0.0
758
+ for cx in candidates:
759
+ collision = False
760
+ for px, py in zip(placed_x, placed_y, strict=False):
761
+ if abs(y - py) < radius_y * 2.0:
762
+ dx = (cx - px) / max(step_x, 1e-9)
763
+ dy = (y - py) / max(radius_y, 1e-9)
764
+ if (dx * dx + dy * dy) < 1.05:
765
+ collision = True
766
+ break
767
+ if not collision:
768
+ best_x = cx
769
+ break
770
+ offsets[idx] = best_x
771
+ placed_x.append(best_x)
772
+ placed_y.append(y)
773
+
774
+ return offsets
775
+
776
+
777
+ def beeswarm_nof_plot(
778
+ df: pd.DataFrame,
779
+ *,
780
+ value_col: str | None = None,
781
+ group_col: str | None = None,
782
+ band_col: str | None = None,
783
+ site_col: str | None = None,
784
+ thresholds: list[tuple[str, float, float]] | None = None,
785
+ nbl_value: float | None = None,
786
+ nbl_label: str = "National Bottom Line",
787
+ highlight_sites: list[str] | None = None,
788
+ log_scale: bool = False,
789
+ palette: dict[str, str] | None = None,
790
+ title: str = "Site Distribution Across NPS-FM Bands",
791
+ subtitle: str | None = None,
792
+ xlabel: str = "",
793
+ ylabel: str | None = None,
794
+ figsize: tuple[float, float] | None = None,
795
+ ax: Axes | None = None,
796
+ config: str | Path | Config | None = None,
797
+ ) -> tuple[Figure, Axes]:
798
+ """Plot a non-overlapping beeswarm distribution of monitoring sites over NOF Band zones.
799
+
800
+ Every individual monitoring site is visible as a packed dot colored by its NOF Grade,
801
+ with optional soft background band zones, a National Bottom Line reference line, and
802
+ labeled callouts for focal ``highlight_sites`` (e.g., community/farm or Impact sites).
803
+
804
+ Returns:
805
+ Tuple of ``(fig, ax)``.
806
+ """
807
+ cfg = ensure_config(config)
808
+ resolved_val = resolve_column(value_col, cfg, "state_value")
809
+ resolved_band = resolve_column(band_col, cfg, "state_band")
810
+ resolved_site = resolve_column(site_col, cfg, "site_id")
811
+ validate_columns(df, [resolved_val], context="beeswarm_nof_plot")
812
+
813
+ work = df.copy()
814
+ work["_val"] = pd.to_numeric(work[resolved_val], errors="coerce")
815
+ work = work.dropna(subset=["_val"]).reset_index(drop=True)
816
+ if work.empty:
817
+ raise ValueError("beeswarm_nof_plot: No valid numeric values to plot.")
818
+
819
+ if group_col is not None:
820
+ validate_columns(work, [group_col], context="beeswarm_nof_plot")
821
+ groups = list(dict.fromkeys(work[group_col].astype(str)))
822
+ work["_grp"] = work[group_col].astype(str)
823
+ else:
824
+ groups = ["All Sites"]
825
+ work["_grp"] = "All Sites"
826
+
827
+ resolved_pal = resolve_palette(palette, cfg, "state_bands")
828
+ highlight_set = set(highlight_sites or [])
829
+
830
+ with mpl_theme(cfg):
831
+ if ax is None:
832
+ fig_w = max(7.5, 2.0 * len(groups) + 2.5)
833
+ fig, ax = plt.subplots(figsize=figsize or (fig_w, 5.8))
834
+ else:
835
+ fig = ax.figure # type: ignore[assignment]
836
+
837
+ # Background NOF band zones
838
+ if thresholds:
839
+ for band_name, low, high in thresholds:
840
+ b_col = resolved_pal.get(band_name, "#e0e0e0")
841
+ ax.axhspan(low, high, facecolor=b_col, alpha=0.14, zorder=0)
842
+ ax.text(
843
+ len(groups) - 0.45,
844
+ (low + high) / 2.0
845
+ if not log_scale
846
+ else math.sqrt(max(low, 1e-6) * max(high, 1e-6)),
847
+ f"Band {band_name}",
848
+ ha="right",
849
+ va="center",
850
+ fontsize=cfg.theme.caption_size - 0.5,
851
+ fontweight="bold",
852
+ color=cfg.theme.caption_color,
853
+ alpha=0.85,
854
+ zorder=1,
855
+ )
856
+
857
+ if nbl_value is not None:
858
+ ax.axhline(nbl_value, color="#c62828", linestyle="--", linewidth=1.6, zorder=2)
859
+ ax.text(
860
+ -0.44,
861
+ nbl_value,
862
+ f" {nbl_label}",
863
+ ha="left",
864
+ va="bottom",
865
+ fontsize=cfg.theme.caption_size - 0.5,
866
+ fontweight="bold",
867
+ color="#c62828",
868
+ zorder=4,
869
+ )
870
+
871
+ y_vals_all = (
872
+ np.log10(np.maximum(work["_val"].to_numpy(), 1e-9))
873
+ if log_scale
874
+ else work["_val"].to_numpy()
875
+ )
876
+ y_span = float(np.ptp(y_vals_all)) or 1.0
877
+ radius_y = y_span * 0.022
878
+
879
+ present_bands: set[str] = set()
880
+ for g_idx, grp_name in enumerate(groups):
881
+ sub = work[work["_grp"] == grp_name].reset_index(drop=True)
882
+ y_raw = sub["_val"].to_numpy(dtype=float)
883
+ y_pack = np.log10(np.maximum(y_raw, 1e-9)) if log_scale else y_raw
884
+ offsets = _pack_beeswarm(y_pack, radius_y=radius_y, step_x=0.055, max_x=0.34)
885
+ xs = g_idx + offsets
886
+
887
+ if resolved_band in sub.columns:
888
+ bands_arr = sub[resolved_band].astype(str).tolist()
889
+ colors = [resolved_pal.get(b, cfg.theme.accent_color) for b in bands_arr]
890
+ present_bands.update(bands_arr)
891
+ else:
892
+ colors = [cfg.theme.accent_color] * len(sub)
893
+
894
+ # Plot regular sites
895
+ ax.scatter(
896
+ xs,
897
+ y_raw,
898
+ s=68,
899
+ c=colors,
900
+ edgecolors="#ffffff",
901
+ linewidths=0.9,
902
+ alpha=0.92,
903
+ zorder=3,
904
+ )
905
+
906
+ # Group median tick
907
+ med = float(np.median(y_raw))
908
+ ax.plot(
909
+ [g_idx - 0.28, g_idx + 0.28],
910
+ [med, med],
911
+ color="#1e2a38",
912
+ linewidth=2.0,
913
+ zorder=4,
914
+ )
915
+
916
+ # Highlighted focal sites
917
+ if highlight_set and resolved_site in sub.columns:
918
+ for i, s_name in enumerate(sub[resolved_site].astype(str)):
919
+ if s_name in highlight_set:
920
+ ax.scatter(
921
+ [xs[i]],
922
+ [y_raw[i]],
923
+ s=155,
924
+ c=[colors[i]],
925
+ edgecolors="#111827",
926
+ linewidths=2.0,
927
+ zorder=5,
928
+ )
929
+ ax.annotate(
930
+ s_name,
931
+ xy=(xs[i], y_raw[i]),
932
+ xytext=(12, 8),
933
+ textcoords="offset points",
934
+ fontsize=cfg.theme.caption_size - 0.5,
935
+ fontweight="bold",
936
+ color="#111827",
937
+ bbox={
938
+ "boxstyle": "round,pad=0.22",
939
+ "facecolor": "#ffffff",
940
+ "edgecolor": "#111827",
941
+ "linewidth": 0.8,
942
+ "alpha": 0.92,
943
+ },
944
+ arrowprops={"arrowstyle": "-", "color": "#111827", "lw": 0.9},
945
+ zorder=6,
946
+ )
947
+
948
+ if log_scale:
949
+ from stplot.theme.mpl import format_log_axis
950
+
951
+ format_log_axis(ax, "y")
952
+
953
+ ax.set_xticks(range(len(groups)))
954
+ ax.set_xticklabels(groups, fontsize=cfg.theme.tick_size, fontweight="bold")
955
+ ax.set_xlim(-0.52, len(groups) - 0.42)
956
+ ax.xaxis.grid(False)
957
+
958
+ if present_bands:
959
+ order = resolve_category_order(None, cfg, "state_bands")
960
+ ordered = [b for b in order if b in present_bands] + [
961
+ b for b in sorted(present_bands) if b not in order
962
+ ]
963
+ handles = [
964
+ plt.Line2D(
965
+ [0],
966
+ [0],
967
+ marker="o",
968
+ color="none",
969
+ markerfacecolor=resolved_pal.get(b, cfg.theme.accent_color),
970
+ markeredgecolor="#ffffff",
971
+ markersize=8,
972
+ label=f"Band {b}",
973
+ )
974
+ for b in ordered
975
+ ]
976
+ handles.append(
977
+ plt.Line2D([0], [0], color="#1e2a38", linewidth=2.0, label="Group Median")
978
+ )
979
+ ax.legend(
980
+ handles=handles,
981
+ loc="upper center",
982
+ bbox_to_anchor=(0.5, -0.11),
983
+ ncol=min(len(handles), 6),
984
+ frameon=False,
985
+ fontsize=cfg.theme.legend_size,
986
+ )
987
+
988
+ style_axes(
989
+ ax,
990
+ title=None,
991
+ xlabel=xlabel,
992
+ ylabel=ylabel or resolved_val,
993
+ config=cfg,
994
+ )
995
+ ax.xaxis.grid(False)
996
+ fig.suptitle(
997
+ title,
998
+ fontsize=cfg.theme.title_size + 1,
999
+ fontweight=cfg.theme.title_weight,
1000
+ color=cfg.theme.text_color,
1001
+ y=0.98,
1002
+ )
1003
+ if subtitle:
1004
+ fig.text(
1005
+ 0.5,
1006
+ 0.92,
1007
+ subtitle,
1008
+ ha="center",
1009
+ va="top",
1010
+ fontsize=cfg.theme.subtitle_size,
1011
+ color=cfg.theme.caption_color,
1012
+ )
1013
+ fig.tight_layout(rect=(0.0, 0.0, 1.0, 0.89 if subtitle else 0.94))
1014
+
1015
+ return fig, ax
1016
+
1017
+
1018
+ def rank_bump_chart(
1019
+ df: pd.DataFrame,
1020
+ *,
1021
+ entity_col: str | None = None,
1022
+ period_col: str | None = None,
1023
+ value_col: str = "Value",
1024
+ higher_is_better: bool = True,
1025
+ already_ranked: bool = False,
1026
+ period_order: list[str] | None = None,
1027
+ highlight_entities: list[str] | None = None,
1028
+ palette: dict[str, str] | None = None,
1029
+ title: str = "FMU Ranking Over Time",
1030
+ subtitle: str | None = None,
1031
+ xlabel: str = "",
1032
+ ylabel: str = "Rank (1 = Best)",
1033
+ figsize: tuple[float, float] | None = None,
1034
+ ax: Axes | None = None,
1035
+ config: str | Path | Config | None = None,
1036
+ ) -> tuple[Figure, Axes]:
1037
+ """Render a smooth bump chart tracking how FMUs or catchments shift in rank over time.
1038
+
1039
+ Computes ranks per period from ``value_col`` (or uses pre-computed integer ranks when
1040
+ ``already_ranked=True``), draws smooth S-curve ribbons with circular rank badges, and
1041
+ annotates start/end ranks plus rank movement (``▲`` / ``▼`` / ``—``).
1042
+
1043
+ Returns:
1044
+ Tuple of ``(fig, ax)``.
1045
+ """
1046
+ cfg = ensure_config(config)
1047
+ resolved_entity = resolve_column(entity_col, cfg, "zone")
1048
+ resolved_period = resolve_column(period_col, cfg, "period")
1049
+ validate_columns(df, [resolved_entity, resolved_period, value_col], context="rank_bump_chart")
1050
+
1051
+ work = df.copy()
1052
+ work["_val"] = pd.to_numeric(work[value_col], errors="coerce")
1053
+ work = work.dropna(subset=["_val"])
1054
+ if work.empty:
1055
+ raise ValueError("rank_bump_chart: No valid numeric values to rank.")
1056
+
1057
+ work["_ent"] = work[resolved_entity].astype(str)
1058
+ work["_per"] = work[resolved_period].astype(str)
1059
+
1060
+ periods = period_order if period_order is not None else sorted(work["_per"].unique().tolist())
1061
+ if len(periods) < 2:
1062
+ raise ValueError("rank_bump_chart: At least 2 periods are required.")
1063
+
1064
+ piv = work.pivot_table(index="_ent", columns="_per", values="_val", aggfunc="mean").reindex(
1065
+ columns=periods
1066
+ )
1067
+ if already_ranked:
1068
+ ranks = piv.copy()
1069
+ else:
1070
+ ranks = piv.rank(axis=0, ascending=not higher_is_better, method="first")
1071
+
1072
+ entities = ranks.sort_values(by=periods[-1]).index.tolist()
1073
+ n_ent = len(entities)
1074
+ n_per = len(periods)
1075
+
1076
+ default_cycle = [
1077
+ "#0077a3",
1078
+ "#2e9e6b",
1079
+ "#e68a00",
1080
+ "#8b5cf6",
1081
+ "#d94663",
1082
+ "#0d9488",
1083
+ "#4f46e5",
1084
+ "#b45309",
1085
+ ]
1086
+ highlight_set = set(highlight_entities or [])
1087
+
1088
+ with mpl_theme(cfg):
1089
+ if ax is None:
1090
+ fig_h = max(4.8, 0.58 * n_ent + 1.8)
1091
+ fig, ax = plt.subplots(figsize=figsize or (11.2, fig_h))
1092
+ else:
1093
+ fig = ax.figure # type: ignore[assignment]
1094
+
1095
+ xs = np.arange(n_per, dtype=float)
1096
+
1097
+ for idx, ent in enumerate(entities):
1098
+ ys = ranks.loc[ent].to_numpy(dtype=float)
1099
+ is_hi = (not highlight_set) or (ent in highlight_set)
1100
+ base_color = (
1101
+ palette[ent]
1102
+ if (palette and ent in palette)
1103
+ else default_cycle[idx % len(default_cycle)]
1104
+ )
1105
+ color = base_color if is_hi else "#cbd5e1"
1106
+ lw = 3.4 if is_hi else 1.8
1107
+ alpha = 0.94 if is_hi else 0.55
1108
+ z = 4 if is_hi else 2
1109
+
1110
+ # Smooth cosine-interpolated S-curves between adjacent periods
1111
+ for p_i in range(n_per - 1):
1112
+ if np.isnan(ys[p_i]) or np.isnan(ys[p_i + 1]):
1113
+ continue
1114
+ t = np.linspace(0.0, 1.0, 40)
1115
+ x_seg = xs[p_i] + t
1116
+ y_seg = ys[p_i] + (ys[p_i + 1] - ys[p_i]) * (0.5 - 0.5 * np.cos(np.pi * t))
1117
+ ax.plot(
1118
+ x_seg,
1119
+ y_seg,
1120
+ color=color,
1121
+ linewidth=lw,
1122
+ alpha=alpha,
1123
+ solid_capstyle="round",
1124
+ zorder=z,
1125
+ )
1126
+
1127
+ # Nodes with rank number inside
1128
+ valid_mask = ~np.isnan(ys)
1129
+ ax.scatter(
1130
+ xs[valid_mask],
1131
+ ys[valid_mask],
1132
+ s=220 if is_hi else 130,
1133
+ color=color,
1134
+ edgecolors="#ffffff",
1135
+ linewidths=1.8,
1136
+ zorder=z + 1,
1137
+ )
1138
+ for p_i in range(n_per):
1139
+ if not np.isnan(ys[p_i]):
1140
+ ax.text(
1141
+ xs[p_i],
1142
+ ys[p_i],
1143
+ f"{int(round(ys[p_i]))}",
1144
+ ha="center",
1145
+ va="center",
1146
+ fontsize=cfg.theme.caption_size - 1,
1147
+ fontweight="bold",
1148
+ color=_contrast_text(color) if is_hi else "#475569",
1149
+ zorder=z + 2,
1150
+ )
1151
+
1152
+ # Start label (left)
1153
+ if not np.isnan(ys[0]):
1154
+ ax.text(
1155
+ -0.16,
1156
+ ys[0],
1157
+ ent,
1158
+ ha="right",
1159
+ va="center",
1160
+ fontsize=cfg.theme.tick_size,
1161
+ fontweight="bold" if is_hi else "normal",
1162
+ color=cfg.theme.text_color if is_hi else cfg.theme.caption_color,
1163
+ )
1164
+
1165
+ # End label + movement delta (right)
1166
+ if not np.isnan(ys[-1]):
1167
+ delta_str = ""
1168
+ if not np.isnan(ys[0]):
1169
+ delta = int(round(ys[0] - ys[-1])) # positive = improved rank
1170
+ if delta > 0:
1171
+ delta_str = f" ▲{delta}"
1172
+ elif delta < 0:
1173
+ delta_str = f" ▼{abs(delta)}"
1174
+ else:
1175
+ delta_str = " —"
1176
+ ax.text(
1177
+ n_per - 1 + 0.16,
1178
+ ys[-1],
1179
+ f"{ent}{delta_str}",
1180
+ ha="left",
1181
+ va="center",
1182
+ fontsize=cfg.theme.tick_size,
1183
+ fontweight="bold" if is_hi else "normal",
1184
+ color=cfg.theme.text_color if is_hi else cfg.theme.caption_color,
1185
+ )
1186
+
1187
+ ax.invert_yaxis()
1188
+ ax.set_xticks(xs)
1189
+ ax.set_xticklabels(periods, fontsize=cfg.theme.tick_size, fontweight="bold")
1190
+ ax.set_yticks([])
1191
+ ax.set_xlim(-1.05, n_per - 1 + 1.25)
1192
+ ax.set_ylim(n_ent + 0.6, 0.4)
1193
+ ax.yaxis.grid(False)
1194
+ ax.xaxis.grid(True, linestyle=":", color=cfg.theme.grid_color, zorder=0)
1195
+ for spine in ["left", "right", "top"]:
1196
+ ax.spines[spine].set_visible(False)
1197
+
1198
+ style_axes(ax, title=None, xlabel=xlabel, ylabel=ylabel, config=cfg)
1199
+ ax.yaxis.grid(False)
1200
+ ax.xaxis.grid(True, linestyle=":", color=cfg.theme.grid_color, zorder=0)
1201
+ for spine in ["left", "right", "top"]:
1202
+ ax.spines[spine].set_visible(False)
1203
+ fig.suptitle(
1204
+ title,
1205
+ fontsize=cfg.theme.title_size + 1,
1206
+ fontweight=cfg.theme.title_weight,
1207
+ color=cfg.theme.text_color,
1208
+ y=0.98,
1209
+ )
1210
+ if subtitle:
1211
+ fig.text(
1212
+ 0.5,
1213
+ 0.915,
1214
+ subtitle,
1215
+ ha="center",
1216
+ va="top",
1217
+ fontsize=cfg.theme.subtitle_size,
1218
+ color=cfg.theme.caption_color,
1219
+ )
1220
+ fig.tight_layout(rect=(0.0, 0.0, 1.0, 0.88 if subtitle else 0.93))
1221
+
1222
+ return fig, ax
1223
+
1224
+
1225
+ def swim_season_calendar(
1226
+ df: pd.DataFrame,
1227
+ *,
1228
+ season_col: str = "Season",
1229
+ month_col: str = "Month",
1230
+ status_col: str = "Status",
1231
+ value_col: str | None = None,
1232
+ month_order: list[str] | None = None,
1233
+ season_order: list[str] | None = None,
1234
+ suitable_values: tuple[str, ...] = ("Green", "Suitable", "Pass", "A", "B"),
1235
+ palette: dict[str, str] | None = None,
1236
+ palette_name: str = "recreational_swim",
1237
+ show_season_summary: bool = True,
1238
+ title: str = "Swim Season Suitability Calendar",
1239
+ subtitle: str | None = None,
1240
+ xlabel: str = "",
1241
+ ylabel: str = "",
1242
+ figsize: tuple[float, float] | None = None,
1243
+ ax: Axes | None = None,
1244
+ config: str | Path | Config | None = None,
1245
+ ) -> tuple[Figure, Axes]:
1246
+ """Render a LAWA-style monthly swim-season calendar strip (season × month tiles).
1247
+
1248
+ Each rounded tile is colored by recreational suitability (e.g., ``Green`` / ``Amber`` /
1249
+ ``Red`` or ``Suitable`` / ``Caution`` / ``Unsuitable``), with an optional right-hand
1250
+ ``% Suitable`` column per season.
1251
+
1252
+ Returns:
1253
+ Tuple of ``(fig, ax)``.
1254
+ """
1255
+ cfg = ensure_config(config)
1256
+ validate_columns(df, [season_col, month_col, status_col], context="swim_season_calendar")
1257
+
1258
+ work = df.copy()
1259
+ if work.empty:
1260
+ raise ValueError("swim_season_calendar: Input DataFrame is empty.")
1261
+
1262
+ work["_s"] = work[season_col].astype(str)
1263
+ work["_m"] = work[month_col].astype(str)
1264
+
1265
+ seasons = season_order if season_order is not None else list(dict.fromkeys(work["_s"]))
1266
+ months = month_order if month_order is not None else list(dict.fromkeys(work["_m"]))
1267
+ resolved_pal = resolve_palette(palette, cfg, palette_name)
1268
+ suit_set = {s.strip().upper() for s in suitable_values}
1269
+
1270
+ piv_status = work.pivot_table(
1271
+ index="_s", columns="_m", values=status_col, aggfunc="first"
1272
+ ).reindex(index=seasons, columns=months)
1273
+ piv_val = (
1274
+ work.pivot_table(index="_s", columns="_m", values=value_col, aggfunc="first").reindex(
1275
+ index=seasons, columns=months
1276
+ )
1277
+ if value_col and value_col in work.columns
1278
+ else None
1279
+ )
1280
+
1281
+ n_rows = len(seasons)
1282
+ n_cols = len(months)
1283
+
1284
+ with mpl_theme(cfg):
1285
+ if ax is None:
1286
+ fig_w = max(7.2, 1.05 * n_cols + (2.6 if show_season_summary else 1.6))
1287
+ fig_h = max(3.6, 0.72 * n_rows + 1.8)
1288
+ fig, ax = plt.subplots(figsize=figsize or (fig_w, fig_h))
1289
+ else:
1290
+ fig = ax.figure # type: ignore[assignment]
1291
+
1292
+ ax.set_facecolor(cfg.theme.background_color)
1293
+ present_statuses: list[str] = []
1294
+
1295
+ for r_idx, season in enumerate(seasons):
1296
+ y = n_rows - 1 - r_idx
1297
+ valid_count = 0
1298
+ suit_count = 0
1299
+ for c_idx, month in enumerate(months):
1300
+ val = piv_status.loc[season, month]
1301
+ if pd.isna(val):
1302
+ color = "#eef1f5"
1303
+ txt = "—"
1304
+ t_col = "#94a3b8"
1305
+ else:
1306
+ status = str(val)
1307
+ if status not in present_statuses:
1308
+ present_statuses.append(status)
1309
+ color = resolved_pal.get(status, "#cbd5e1")
1310
+ t_col = _contrast_text(color)
1311
+ valid_count += 1
1312
+ if status.strip().upper() in suit_set:
1313
+ suit_count += 1
1314
+ if piv_val is not None and not pd.isna(piv_val.loc[season, month]):
1315
+ txt = str(piv_val.loc[season, month])
1316
+ else:
1317
+ txt = status[:1].upper()
1318
+
1319
+ ax.add_patch(
1320
+ FancyBboxPatch(
1321
+ (c_idx + 0.08, y + 0.12),
1322
+ 0.84,
1323
+ 0.76,
1324
+ boxstyle="round,pad=0.02,rounding_size=0.14",
1325
+ facecolor=color,
1326
+ edgecolor="#ffffff",
1327
+ linewidth=1.5,
1328
+ zorder=2,
1329
+ )
1330
+ )
1331
+ ax.text(
1332
+ c_idx + 0.5,
1333
+ y + 0.5,
1334
+ txt,
1335
+ ha="center",
1336
+ va="center",
1337
+ fontsize=cfg.theme.tick_size,
1338
+ fontweight="bold",
1339
+ color=t_col,
1340
+ zorder=3,
1341
+ )
1342
+
1343
+ if show_season_summary:
1344
+ pct = 100.0 * suit_count / valid_count if valid_count > 0 else 0.0
1345
+ ax.text(
1346
+ n_cols + 0.25,
1347
+ y + 0.5,
1348
+ f"{pct:.0f}%",
1349
+ ha="left",
1350
+ va="center",
1351
+ fontsize=cfg.theme.tick_size,
1352
+ fontweight="bold",
1353
+ color="#2e7d32" if pct >= 80 else ("#b45309" if pct >= 50 else "#c62828"),
1354
+ )
1355
+
1356
+ if show_season_summary:
1357
+ ax.text(
1358
+ n_cols + 0.25,
1359
+ n_rows + 0.15,
1360
+ "% Suitable",
1361
+ ha="left",
1362
+ va="bottom",
1363
+ fontsize=cfg.theme.caption_size,
1364
+ fontweight="bold",
1365
+ color=cfg.theme.caption_color,
1366
+ )
1367
+
1368
+ ax.set_xticks([i + 0.5 for i in range(n_cols)])
1369
+ ax.set_xticklabels(months, fontsize=cfg.theme.tick_size, fontweight="bold")
1370
+ ax.xaxis.tick_top()
1371
+ ax.set_yticks([n_rows - 1 - i + 0.5 for i in range(n_rows)])
1372
+ ax.set_yticklabels(seasons, fontsize=cfg.theme.tick_size, fontweight="bold")
1373
+ ax.tick_params(length=0, pad=6)
1374
+ ax.set_xlim(0, n_cols + (1.35 if show_season_summary else 0.15))
1375
+ ax.set_ylim(-0.05, n_rows + 0.15)
1376
+ for spine in ax.spines.values():
1377
+ spine.set_visible(False)
1378
+
1379
+ if present_statuses:
1380
+ handles = [
1381
+ FancyBboxPatch(
1382
+ (0, 0),
1383
+ 1,
1384
+ 1,
1385
+ boxstyle="round,pad=0.1",
1386
+ facecolor=resolved_pal.get(s, "#cbd5e1"),
1387
+ edgecolor="none",
1388
+ )
1389
+ for s in present_statuses
1390
+ ]
1391
+ ax.legend(
1392
+ handles,
1393
+ present_statuses,
1394
+ loc="upper center",
1395
+ bbox_to_anchor=(0.45, -0.06),
1396
+ ncol=min(len(present_statuses), 5),
1397
+ frameon=False,
1398
+ fontsize=cfg.theme.legend_size,
1399
+ )
1400
+
1401
+ fig.suptitle(
1402
+ title,
1403
+ fontsize=cfg.theme.title_size + 1,
1404
+ fontweight=cfg.theme.title_weight,
1405
+ color=cfg.theme.text_color,
1406
+ y=0.98,
1407
+ )
1408
+ if subtitle:
1409
+ fig.text(
1410
+ 0.5,
1411
+ 0.915,
1412
+ subtitle,
1413
+ ha="center",
1414
+ va="top",
1415
+ fontsize=cfg.theme.subtitle_size,
1416
+ color=cfg.theme.caption_color,
1417
+ )
1418
+ fig.subplots_adjust(top=0.80 if subtitle else 0.85, bottom=0.14)
1419
+
1420
+ return fig, ax
1421
+
1422
+
1423
+ def intervention_spotlight_card(
1424
+ *,
1425
+ site_name: str,
1426
+ intervention_title: str,
1427
+ indicator_label: str,
1428
+ before_grade: str,
1429
+ after_grade: str,
1430
+ before_value: float,
1431
+ after_value: float,
1432
+ unit: str = "",
1433
+ before_period: str = "Before",
1434
+ after_period: str = "After",
1435
+ indicator: str | None = None,
1436
+ indicator_directions: dict[str, str] | None = None,
1437
+ lower_is_better: bool | None = None,
1438
+ timeseries_df: pd.DataFrame | None = None,
1439
+ period_col: str | None = None,
1440
+ value_col: str | None = None,
1441
+ intervention_index: float | None = None,
1442
+ intervention_label: str = "Upgrade",
1443
+ summary_note: str | None = None,
1444
+ palette: dict[str, str] | None = None,
1445
+ figsize: tuple[float, float] = (10.8, 4.6),
1446
+ config: str | Path | Config | None = None,
1447
+ ) -> tuple[Figure, Axes]:
1448
+ """Render a Before-and-After catchment intervention / upgrade spotlight card.
1449
+
1450
+ Pairs **Before** vs **After** NPS-FM grade badges and a bold headline ``% change``
1451
+ callout with a mini trend sparkline (when ``timeseries_df`` is provided) or a
1452
+ Before/After comparison bar.
1453
+
1454
+ When ``lower_is_better`` is ``None``, polarity is resolved from ``indicator`` (or
1455
+ ``indicator_label``) via ``indicator_directions`` / ``config.indicator_directions``.
1456
+
1457
+ Returns:
1458
+ Tuple of ``(fig, ax)`` where ``ax`` is the primary card canvas.
1459
+ """
1460
+ from stplot.config import is_lower_better
1461
+
1462
+ cfg = ensure_config(config)
1463
+ resolved_pal = resolve_palette(palette, cfg, "state_bands")
1464
+ resolved_lower_better = is_lower_better(
1465
+ indicator or indicator_label,
1466
+ cfg,
1467
+ lower_is_better=lower_is_better,
1468
+ overrides=indicator_directions,
1469
+ default=True,
1470
+ )
1471
+
1472
+ pct_change = (
1473
+ 100.0 * (after_value - before_value) / abs(before_value) if before_value != 0 else 0.0
1474
+ )
1475
+ improved = (pct_change < 0) if resolved_lower_better else (pct_change > 0)
1476
+ kpi_color = "#2e7d32" if improved else ("#c62828" if pct_change != 0 else "#475569")
1477
+ kpi_text = f"{pct_change:+.0f}%"
1478
+
1479
+ with mpl_theme(cfg):
1480
+ fig = plt.figure(figsize=figsize, facecolor="#ffffff")
1481
+ ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
1482
+ ax.set_xlim(0, 10)
1483
+ ax.set_ylim(0, 5)
1484
+ ax.axis("off")
1485
+
1486
+ # Card outer frame
1487
+ ax.add_patch(
1488
+ FancyBboxPatch(
1489
+ (0.15, 0.15),
1490
+ 9.7,
1491
+ 4.7,
1492
+ boxstyle="round,pad=0.02,rounding_size=0.18",
1493
+ facecolor="#f9fbfd",
1494
+ edgecolor="#d7e0ea",
1495
+ linewidth=1.5,
1496
+ zorder=1,
1497
+ )
1498
+ )
1499
+
1500
+ # Header banner
1501
+ ax.add_patch(
1502
+ FancyBboxPatch(
1503
+ (0.15, 3.85),
1504
+ 9.7,
1505
+ 1.0,
1506
+ boxstyle="round,pad=0.02,rounding_size=0.18",
1507
+ facecolor=cfg.theme.accent_color,
1508
+ edgecolor="none",
1509
+ zorder=2,
1510
+ )
1511
+ )
1512
+ ax.text(
1513
+ 0.48,
1514
+ 4.48,
1515
+ intervention_title,
1516
+ ha="left",
1517
+ va="center",
1518
+ fontsize=cfg.theme.title_size + 1,
1519
+ fontweight="bold",
1520
+ color="#ffffff",
1521
+ zorder=3,
1522
+ )
1523
+ ax.text(
1524
+ 0.48,
1525
+ 4.10,
1526
+ f"{site_name} • {indicator_label}",
1527
+ ha="left",
1528
+ va="center",
1529
+ fontsize=cfg.theme.subtitle_size,
1530
+ color="#e2f1f8",
1531
+ zorder=3,
1532
+ )
1533
+
1534
+ # Left panel: Before -> After grade badges
1535
+ b_col = resolved_pal.get(before_grade, "#94a3b8")
1536
+ a_col = resolved_pal.get(after_grade, "#2e9e6b")
1537
+
1538
+ def _draw_badge(x0: float, grade: str, col: str, period_txt: str, val: float) -> None:
1539
+ ax.add_patch(
1540
+ FancyBboxPatch(
1541
+ (x0, 2.15),
1542
+ 1.35,
1543
+ 1.22,
1544
+ boxstyle="round,pad=0.02,rounding_size=0.16",
1545
+ facecolor=col,
1546
+ edgecolor="#ffffff",
1547
+ linewidth=2.0,
1548
+ zorder=3,
1549
+ )
1550
+ )
1551
+ ax.text(
1552
+ x0 + 0.675,
1553
+ 2.82,
1554
+ grade,
1555
+ ha="center",
1556
+ va="center",
1557
+ fontsize=24,
1558
+ fontweight="bold",
1559
+ color=_contrast_text(col),
1560
+ zorder=4,
1561
+ )
1562
+ ax.text(
1563
+ x0 + 0.675,
1564
+ 2.32,
1565
+ period_txt,
1566
+ ha="center",
1567
+ va="center",
1568
+ fontsize=cfg.theme.caption_size - 0.5,
1569
+ fontweight="bold",
1570
+ color=_contrast_text(col),
1571
+ alpha=0.92,
1572
+ zorder=4,
1573
+ )
1574
+ val_str = f"{val:g} {unit}".strip()
1575
+ ax.text(
1576
+ x0 + 0.675,
1577
+ 1.86,
1578
+ val_str,
1579
+ ha="center",
1580
+ va="center",
1581
+ fontsize=cfg.theme.tick_size,
1582
+ fontweight="bold",
1583
+ color=cfg.theme.text_color,
1584
+ zorder=4,
1585
+ )
1586
+
1587
+ _draw_badge(0.55, before_grade, b_col, before_period, before_value)
1588
+ ax.annotate(
1589
+ "",
1590
+ xy=(2.72, 2.76),
1591
+ xytext=(2.05, 2.76),
1592
+ arrowprops={"arrowstyle": "-|>", "color": cfg.theme.text_color, "lw": 2.8},
1593
+ zorder=4,
1594
+ )
1595
+ _draw_badge(2.85, after_grade, a_col, after_period, after_value)
1596
+
1597
+ # Headline % change callout pill
1598
+ ax.add_patch(
1599
+ FancyBboxPatch(
1600
+ (0.55, 0.78),
1601
+ 3.65,
1602
+ 0.80,
1603
+ boxstyle="round,pad=0.02,rounding_size=0.14",
1604
+ facecolor="#ffffff",
1605
+ edgecolor=kpi_color,
1606
+ linewidth=1.8,
1607
+ zorder=3,
1608
+ )
1609
+ )
1610
+ ax.text(
1611
+ 1.45,
1612
+ 1.18,
1613
+ kpi_text,
1614
+ ha="center",
1615
+ va="center",
1616
+ fontsize=22,
1617
+ fontweight="bold",
1618
+ color=kpi_color,
1619
+ zorder=4,
1620
+ )
1621
+ change_desc = (
1622
+ "Reduction" if pct_change < 0 else ("Increase" if pct_change > 0 else "No change")
1623
+ )
1624
+ ax.text(
1625
+ 2.45,
1626
+ 1.28,
1627
+ change_desc,
1628
+ ha="left",
1629
+ va="center",
1630
+ fontsize=cfg.theme.tick_size,
1631
+ fontweight="bold",
1632
+ color=cfg.theme.text_color,
1633
+ zorder=4,
1634
+ )
1635
+ ax.text(
1636
+ 2.45,
1637
+ 0.98,
1638
+ "Post-intervention",
1639
+ ha="left",
1640
+ va="center",
1641
+ fontsize=cfg.theme.caption_size - 0.5,
1642
+ color=cfg.theme.caption_color,
1643
+ zorder=4,
1644
+ )
1645
+
1646
+ # Right panel: Mini trend sparkline or Before/After comparison bar
1647
+ ax_sub = fig.add_axes([0.505, 0.22, 0.445, 0.49])
1648
+ ax_sub.set_facecolor("#ffffff")
1649
+
1650
+ if timeseries_df is not None and not timeseries_df.empty:
1651
+ p_col = resolve_column(period_col, cfg, "period")
1652
+ v_col = resolve_column(value_col, cfg, "state_value")
1653
+ validate_columns(timeseries_df, [p_col, v_col], context="intervention_spotlight_card")
1654
+ ts = timeseries_df.copy().reset_index(drop=True)
1655
+ xs_ts = np.arange(len(ts), dtype=float)
1656
+ ys_ts = pd.to_numeric(ts[v_col], errors="coerce").to_numpy(dtype=float)
1657
+
1658
+ split_x = (
1659
+ float(intervention_index) if intervention_index is not None else (len(ts) - 1) / 2.0
1660
+ )
1661
+ ax_sub.axvspan(-0.3, split_x, facecolor=b_col, alpha=0.10, zorder=0)
1662
+ ax_sub.axvspan(split_x, len(ts) - 0.7, facecolor=a_col, alpha=0.12, zorder=0)
1663
+ ax_sub.axvline(
1664
+ split_x, color=cfg.theme.text_color, linestyle="--", linewidth=1.4, zorder=2
1665
+ )
1666
+ ax_sub.text(
1667
+ split_x + 0.12,
1668
+ float(np.nanmax(ys_ts)) * 0.98,
1669
+ intervention_label,
1670
+ ha="left",
1671
+ va="top",
1672
+ fontsize=cfg.theme.caption_size - 0.5,
1673
+ fontweight="bold",
1674
+ color=cfg.theme.text_color,
1675
+ zorder=4,
1676
+ )
1677
+
1678
+ ax_sub.plot(
1679
+ xs_ts,
1680
+ ys_ts,
1681
+ color=cfg.theme.accent_color,
1682
+ linewidth=2.4,
1683
+ marker="o",
1684
+ markersize=5.5,
1685
+ zorder=3,
1686
+ )
1687
+ ax_sub.fill_between(xs_ts, ys_ts, color=cfg.theme.accent_color, alpha=0.08, zorder=1)
1688
+ step = max(1, math.ceil(len(ts) / 6))
1689
+ tick_idx = list(range(0, len(ts), step))
1690
+ if (len(ts) - 1) not in tick_idx:
1691
+ tick_idx.append(len(ts) - 1)
1692
+ ax_sub.set_xticks(tick_idx)
1693
+ ax_sub.set_xticklabels(
1694
+ [str(ts[p_col].iloc[i]) for i in tick_idx],
1695
+ fontsize=cfg.theme.caption_size - 0.5,
1696
+ )
1697
+ ax_sub.set_ylabel(unit, fontsize=cfg.theme.caption_size)
1698
+ ax_sub.set_xlim(-0.3, len(ts) - 0.7)
1699
+ ax_sub.set_ylim(bottom=0, top=float(np.nanmax(ys_ts)) * 1.15)
1700
+ else:
1701
+ ax_sub.bar(
1702
+ [0, 1], [before_value, after_value], color=[b_col, a_col], width=0.52, zorder=3
1703
+ )
1704
+ ax_sub.set_xticks([0, 1])
1705
+ ax_sub.set_xticklabels(
1706
+ [before_period, after_period], fontsize=cfg.theme.tick_size, fontweight="bold"
1707
+ )
1708
+ ax_sub.set_ylabel(unit, fontsize=cfg.theme.caption_size)
1709
+ ax_sub.set_ylim(0, max(before_value, after_value) * 1.25)
1710
+
1711
+ ax_sub.yaxis.grid(True, linestyle=":", color=cfg.theme.grid_color, zorder=0)
1712
+ ax_sub.xaxis.grid(False)
1713
+ ax_sub.spines["top"].set_visible(False)
1714
+ ax_sub.spines["right"].set_visible(False)
1715
+
1716
+ if summary_note:
1717
+ ax.text(
1718
+ 0.48,
1719
+ 0.42,
1720
+ summary_note,
1721
+ ha="left",
1722
+ va="center",
1723
+ fontsize=cfg.theme.caption_size,
1724
+ style="italic",
1725
+ color=cfg.theme.caption_color,
1726
+ zorder=4,
1727
+ )
1728
+
1729
+ return fig, ax
1730
+
1731
+
1732
+ def top_bottom_sites_plot(
1733
+ df: pd.DataFrame,
1734
+ *,
1735
+ n: int = 5,
1736
+ site_col: str | None = None,
1737
+ value_col: str | None = None,
1738
+ band_col: str | None = None,
1739
+ trend_col: str | None = None,
1740
+ indicator_col: str | None = None,
1741
+ indicator: str | None = None,
1742
+ lower_is_better: bool | None = None,
1743
+ indicator_directions: dict[str, str] | None = None,
1744
+ unit: str = "",
1745
+ log_scale: bool = False,
1746
+ show_median_line: bool = True,
1747
+ median_label: str = "Regional Median",
1748
+ palette: dict[str, str] | None = None,
1749
+ palette_name: str = "state_bands",
1750
+ title: str = "Best & Worst Performing Sites",
1751
+ subtitle: str | None = None,
1752
+ xlabel: str | None = None,
1753
+ figsize: tuple[float, float] | None = None,
1754
+ config: str | Path | Config | None = None,
1755
+ ) -> tuple[Figure, tuple[Axes, Axes]]:
1756
+ """Plot the Best ``n`` and Worst ``n`` sites on a shared scale with a Regional Median line.
1757
+
1758
+ Automatically resolves indicator polarity via ``config.indicator_directions`` (lowest values
1759
+ = Best for DRP/E. coli; highest values = Best for Clarity/MCI) and plots each site colored
1760
+ by its State Band alongside optional directional trend symbols (``↗`` / ``→`` / ``↘``).
1761
+
1762
+ Returns:
1763
+ Tuple of ``(fig, (ax_best, ax_worst))``.
1764
+ """
1765
+ from stplot.theme.mpl import format_log_axis
1766
+ from stplot.transform.tables import select_top_bottom_sites
1767
+
1768
+ cfg = ensure_config(config)
1769
+ r_site = resolve_column(site_col, cfg, "site_id")
1770
+ r_val = resolve_column(value_col, cfg, "state_value")
1771
+ r_band = band_col if band_col is not None else cfg.columns.get("state_band")
1772
+ r_trend = trend_col if trend_col is not None else cfg.columns.get("trend_direction")
1773
+ validate_columns(df, [r_site, r_val], context="top_bottom_sites_plot")
1774
+
1775
+ all_vals = pd.to_numeric(df[r_val], errors="coerce").dropna()
1776
+ if log_scale:
1777
+ all_vals = all_vals[all_vals > 0]
1778
+ if all_vals.empty:
1779
+ raise ValueError("top_bottom_sites_plot: No valid numeric values to plot.")
1780
+ reg_median = float(all_vals.median())
1781
+
1782
+ work_df = df.copy()
1783
+ if log_scale:
1784
+ work_df = work_df[pd.to_numeric(work_df[r_val], errors="coerce") > 0].copy()
1785
+
1786
+ selected = select_top_bottom_sites(
1787
+ work_df,
1788
+ n=n,
1789
+ value_col=r_val,
1790
+ indicator_col=indicator_col,
1791
+ indicator=indicator,
1792
+ lower_is_better=lower_is_better,
1793
+ indicator_directions=indicator_directions,
1794
+ group_label_col="_rank_grp",
1795
+ config=cfg,
1796
+ )
1797
+ groups = list(dict.fromkeys(selected["_rank_grp"].tolist()))
1798
+ best_df = selected[selected["_rank_grp"] == groups[0]].reset_index(drop=True)
1799
+ worst_df = (
1800
+ selected[selected["_rank_grp"] == groups[1]].reset_index(drop=True)
1801
+ if len(groups) > 1
1802
+ else pd.DataFrame(columns=selected.columns)
1803
+ )
1804
+
1805
+ pal = resolve_palette(palette, cfg, palette_name)
1806
+ sym_map = {"Improving": "↗", "Indeterminate": "→", "Degrading": "↘"}
1807
+ sel_vals = pd.to_numeric(selected[r_val], errors="coerce")
1808
+ xmin = float(sel_vals.min()) * 0.5 if log_scale else 0.0
1809
+ xmax = float(sel_vals.max()) * (2.6 if log_scale else 1.24)
1810
+
1811
+ with mpl_theme(cfg):
1812
+ n_rows = max(len(best_df), 1) + max(len(worst_df), 1)
1813
+ fig_h = max(5.2, 0.48 * n_rows + 2.4)
1814
+ fig, (ax_top, ax_bot) = plt.subplots(
1815
+ 2,
1816
+ 1,
1817
+ figsize=figsize or (10.6, fig_h),
1818
+ sharex=True,
1819
+ gridspec_kw={
1820
+ "height_ratios": [max(len(best_df), 1), max(len(worst_df), 1)],
1821
+ "hspace": 0.34,
1822
+ },
1823
+ )
1824
+
1825
+ def _plot_panel(ax_p: Axes, sub: pd.DataFrame, header: str, accent: str) -> None:
1826
+ if sub.empty:
1827
+ ax_p.axis("off")
1828
+ return
1829
+ ys = np.arange(len(sub))[::-1]
1830
+ vals = pd.to_numeric(sub[r_val], errors="coerce").to_numpy(dtype=float)
1831
+ colors = [
1832
+ pal.get(str(b), cfg.theme.accent_color)
1833
+ for b in (sub[r_band] if (r_band and r_band in sub.columns) else [None] * len(sub))
1834
+ ]
1835
+ if log_scale:
1836
+ ax_p.barh(
1837
+ ys,
1838
+ vals - xmin,
1839
+ left=xmin,
1840
+ height=0.62,
1841
+ color=colors,
1842
+ edgecolor="#ffffff",
1843
+ lw=0.8,
1844
+ zorder=3,
1845
+ )
1846
+ else:
1847
+ ax_p.barh(
1848
+ ys, vals, height=0.62, color=colors, edgecolor="#ffffff", lw=0.8, zorder=3
1849
+ )
1850
+ if show_median_line:
1851
+ ax_p.axvline(
1852
+ reg_median,
1853
+ color="#1e2a38",
1854
+ linestyle="--",
1855
+ linewidth=1.4,
1856
+ zorder=4,
1857
+ )
1858
+ for idx, (y, v) in enumerate(zip(ys, vals, strict=True)):
1859
+ parts = [f"{v:g} {unit}".strip()]
1860
+ if r_band and r_band in sub.columns and pd.notna(sub[r_band].iloc[idx]):
1861
+ parts.append(f"({sub[r_band].iloc[idx]})")
1862
+ if r_trend and r_trend in sub.columns and pd.notna(sub[r_trend].iloc[idx]):
1863
+ tr = str(sub[r_trend].iloc[idx])
1864
+ if tr in sym_map:
1865
+ parts.append(sym_map[tr])
1866
+ txt_x = v * 1.12 if log_scale else (v + xmax * 0.015)
1867
+ ax_p.text(
1868
+ txt_x,
1869
+ y,
1870
+ " ".join(parts),
1871
+ ha="left",
1872
+ va="center",
1873
+ fontsize=cfg.theme.caption_size,
1874
+ fontweight="bold",
1875
+ color=cfg.theme.text_color,
1876
+ zorder=5,
1877
+ )
1878
+ ax_p.set_yticks(ys)
1879
+ ax_p.set_yticklabels(
1880
+ sub[r_site].astype(str).tolist(),
1881
+ fontsize=cfg.theme.tick_size,
1882
+ fontweight="bold",
1883
+ )
1884
+ ax_p.set_xlim(xmin, xmax)
1885
+ if log_scale:
1886
+ format_log_axis(ax_p, "x")
1887
+ ax_p.set_title(
1888
+ header,
1889
+ loc="left",
1890
+ fontsize=cfg.theme.label_size,
1891
+ fontweight="bold",
1892
+ color=accent,
1893
+ pad=6,
1894
+ )
1895
+ style_axes(ax_p, title=None, config=cfg)
1896
+ ax_p.yaxis.grid(False)
1897
+
1898
+ _plot_panel(ax_top, best_df, f"Best {len(best_df)} Sites", "#2e7d32")
1899
+ _plot_panel(ax_bot, worst_df, f"Worst {len(worst_df)} Sites", "#c62828")
1900
+
1901
+ if show_median_line and not best_df.empty:
1902
+ med_x = reg_median * 1.10 if log_scale else (reg_median + xmax * 0.012)
1903
+ ax_top.text(
1904
+ med_x,
1905
+ len(best_df) - 0.55,
1906
+ f"{median_label}: {reg_median:g} {unit}".strip(),
1907
+ ha="left",
1908
+ va="top",
1909
+ fontsize=cfg.theme.caption_size - 0.5,
1910
+ fontweight="bold",
1911
+ color="#1e2a38",
1912
+ bbox={"boxstyle": "round,pad=0.18", "facecolor": "#ffffff", "edgecolor": "#cbd5e1"},
1913
+ zorder=6,
1914
+ )
1915
+
1916
+ ax_bot.set_xlabel(
1917
+ xlabel or f"{r_val} ({unit})" if unit else (xlabel or r_val),
1918
+ fontsize=cfg.theme.label_size,
1919
+ color=cfg.theme.text_color,
1920
+ )
1921
+ fig.suptitle(
1922
+ title,
1923
+ fontsize=cfg.theme.title_size + 1,
1924
+ fontweight=cfg.theme.title_weight,
1925
+ color=cfg.theme.text_color,
1926
+ y=0.98,
1927
+ )
1928
+ if subtitle:
1929
+ fig.text(
1930
+ 0.5,
1931
+ 0.925,
1932
+ subtitle,
1933
+ ha="center",
1934
+ va="top",
1935
+ fontsize=cfg.theme.subtitle_size,
1936
+ color=cfg.theme.caption_color,
1937
+ )
1938
+ fig.subplots_adjust(left=0.28, right=0.96, top=0.84 if subtitle else 0.89, bottom=0.10)
1939
+
1940
+ return fig, (ax_top, ax_bot)