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.
- stplot/__init__.py +21 -0
- stplot/config/__init__.py +33 -0
- stplot/config/loader.py +106 -0
- stplot/config/models.py +328 -0
- stplot/config/presets/__init__.py +1 -0
- stplot/config/presets/default.yaml +208 -0
- stplot/config/presets/horizons_one_plan.yaml +59 -0
- stplot/io/__init__.py +6 -0
- stplot/io/spatial.py +72 -0
- stplot/io/tabular.py +154 -0
- stplot/plots/__init__.py +122 -0
- stplot/plots/barbell.py +400 -0
- stplot/plots/batch.py +135 -0
- stplot/plots/domains.py +1143 -0
- stplot/plots/executive.py +474 -0
- stplot/plots/export.py +74 -0
- stplot/plots/infographics.py +1118 -0
- stplot/plots/lollipop.py +285 -0
- stplot/plots/maps.py +738 -0
- stplot/plots/matrix.py +190 -0
- stplot/plots/one_plan.py +642 -0
- stplot/plots/paired.py +437 -0
- stplot/plots/scorecards.py +1940 -0
- stplot/plots/state.py +373 -0
- stplot/plots/state_trends.py +1413 -0
- stplot/plots/tables.py +107 -0
- stplot/plots/timeseries.py +607 -0
- stplot/plots/trends.py +305 -0
- stplot/reporting/__init__.py +24 -0
- stplot/reporting/captions.py +177 -0
- stplot/reporting/html_companion.py +339 -0
- stplot/reporting/templates.py +485 -0
- stplot/reporting/word.py +369 -0
- stplot/theme/__init__.py +25 -0
- stplot/theme/folium.py +62 -0
- stplot/theme/mpl.py +181 -0
- stplot/theme/plotly.py +130 -0
- stplot/transform/__init__.py +60 -0
- stplot/transform/categories.py +51 -0
- stplot/transform/columns.py +103 -0
- stplot/transform/filters.py +385 -0
- stplot/transform/merge.py +173 -0
- stplot/transform/pairing.py +154 -0
- stplot/transform/qa.py +297 -0
- stplot/transform/tables.py +573 -0
- stplot/transform/zones.py +354 -0
- stplot-0.1.0.dist-info/METADATA +235 -0
- stplot-0.1.0.dist-info/RECORD +49 -0
- stplot-0.1.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,1413 @@
|
|
|
1
|
+
"""Combined State + Trend visualization templates for simultaneous assessment."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import textwrap
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import matplotlib.colors as mcolors
|
|
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 FancyBboxPatch, 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
|
+
from stplot.transform.filters import derive_trend_direction_3level
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _contrast_text(hex_color: str) -> str:
|
|
31
|
+
cleaned = str(hex_color).lstrip("#")
|
|
32
|
+
if len(cleaned) != 6:
|
|
33
|
+
return "#1e2a38"
|
|
34
|
+
r, g, b = int(cleaned[0:2], 16), int(cleaned[2:4], 16), int(cleaned[4:6], 16)
|
|
35
|
+
return "#111111" if (0.299 * r + 0.587 * g + 0.114 * b) > 150 else "#ffffff"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _normalize_trend_3level(df: pd.DataFrame, trend_col: str, cfg: Config) -> pd.Series:
|
|
39
|
+
"""Ensure a 3-level trend series (Improving / Indeterminate / Degrading / Not Analysed)."""
|
|
40
|
+
raw = df[trend_col].astype(str).str.strip()
|
|
41
|
+
known_3 = {"Improving", "Indeterminate", "Degrading", "Not Analysed"}
|
|
42
|
+
if raw.isin(known_3).mean() >= 0.5:
|
|
43
|
+
return raw
|
|
44
|
+
derived = derive_trend_direction_3level(
|
|
45
|
+
df,
|
|
46
|
+
confidence_col=trend_col,
|
|
47
|
+
output_col="_trend_3",
|
|
48
|
+
config=cfg,
|
|
49
|
+
)
|
|
50
|
+
return derived["_trend_3"].astype(str)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def state_trend_butterfly(
|
|
54
|
+
df: pd.DataFrame,
|
|
55
|
+
*,
|
|
56
|
+
group_col: str | None = None,
|
|
57
|
+
band_col: str | None = None,
|
|
58
|
+
trend_col: str | None = None,
|
|
59
|
+
band_order: list[str] | None = None,
|
|
60
|
+
group_order: list[str] | None = None,
|
|
61
|
+
state_palette: dict[str, str] | None = None,
|
|
62
|
+
trend_palette: dict[str, str] | None = None,
|
|
63
|
+
state_palette_name: str = "state_bands",
|
|
64
|
+
title: str = "State & Trends Overview by FMU",
|
|
65
|
+
subtitle: str | None = None,
|
|
66
|
+
state_xlabel: str = "Current State (% of Sites)",
|
|
67
|
+
trend_xlabel: str = "← % Degrading | % Improving →",
|
|
68
|
+
figsize: tuple[float, float] | None = None,
|
|
69
|
+
config: str | Path | Config | None = None,
|
|
70
|
+
) -> tuple[Figure, tuple[Axes, Axes]]:
|
|
71
|
+
"""Plot a paired State (left) + Diverging Trend (right) butterfly chart on a shared y-axis.
|
|
72
|
+
|
|
73
|
+
Allows instant row-by-row comparison of current water quality state (100% stacked NOF
|
|
74
|
+
grades or One Plan Pass/Fail) alongside trend trajectory (`% Degrading` vs `% Improving`).
|
|
75
|
+
|
|
76
|
+
Returns:
|
|
77
|
+
Tuple of ``(fig, (ax_state, ax_trend))``.
|
|
78
|
+
"""
|
|
79
|
+
cfg = ensure_config(config)
|
|
80
|
+
r_group = resolve_column(group_col, cfg, "zone")
|
|
81
|
+
r_band = resolve_column(band_col, cfg, "state_band")
|
|
82
|
+
r_trend = resolve_column(trend_col, cfg, "trend_direction")
|
|
83
|
+
validate_columns(df, [r_group, r_band, r_trend], context="state_trend_butterfly")
|
|
84
|
+
|
|
85
|
+
work = df.copy()
|
|
86
|
+
if work.empty:
|
|
87
|
+
raise ValueError("state_trend_butterfly: Input DataFrame is empty.")
|
|
88
|
+
|
|
89
|
+
work["_grp"] = work[r_group].astype(str)
|
|
90
|
+
work["_band"] = work[r_band].astype(str)
|
|
91
|
+
work["_trend"] = _normalize_trend_3level(work, r_trend, cfg)
|
|
92
|
+
|
|
93
|
+
groups = group_order if group_order is not None else list(dict.fromkeys(work["_grp"].tolist()))
|
|
94
|
+
bands_present = list(dict.fromkeys(work["_band"].tolist()))
|
|
95
|
+
cfg_order = resolve_category_order(band_order, cfg, state_palette_name)
|
|
96
|
+
bands = [b for b in cfg_order if b in bands_present] + [
|
|
97
|
+
b for b in bands_present if b not in cfg_order
|
|
98
|
+
]
|
|
99
|
+
|
|
100
|
+
s_pal = resolve_palette(state_palette, cfg, state_palette_name)
|
|
101
|
+
t_pal = resolve_palette(trend_palette, cfg, "trend_directions")
|
|
102
|
+
|
|
103
|
+
n_grp = len(groups)
|
|
104
|
+
ys = np.arange(n_grp)[::-1]
|
|
105
|
+
|
|
106
|
+
with mpl_theme(cfg):
|
|
107
|
+
fig_h = max(4.2, 0.62 * n_grp + 2.0)
|
|
108
|
+
fig, (ax_state, ax_trend) = plt.subplots(
|
|
109
|
+
1,
|
|
110
|
+
2,
|
|
111
|
+
figsize=figsize or (12.6, fig_h),
|
|
112
|
+
sharey=True,
|
|
113
|
+
gridspec_kw={"width_ratios": [1.05, 1.0], "wspace": 0.08},
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
# Left panel: 100% stacked State bands
|
|
117
|
+
state_ct = pd.crosstab(work["_grp"], work["_band"]).reindex(
|
|
118
|
+
index=groups, columns=bands, fill_value=0
|
|
119
|
+
)
|
|
120
|
+
state_totals = state_ct.sum(axis=1).replace(0, 1)
|
|
121
|
+
state_pct = state_ct.div(state_totals, axis=0) * 100.0
|
|
122
|
+
|
|
123
|
+
left_acc = np.zeros(n_grp, dtype=float)
|
|
124
|
+
for band in bands:
|
|
125
|
+
vals = state_pct[band].to_numpy(dtype=float)
|
|
126
|
+
col = s_pal.get(band, "#bdbdbd")
|
|
127
|
+
ax_state.barh(
|
|
128
|
+
ys,
|
|
129
|
+
vals,
|
|
130
|
+
left=left_acc,
|
|
131
|
+
height=0.62,
|
|
132
|
+
color=col,
|
|
133
|
+
edgecolor="#ffffff",
|
|
134
|
+
linewidth=0.8,
|
|
135
|
+
label=band,
|
|
136
|
+
zorder=3,
|
|
137
|
+
)
|
|
138
|
+
for idx, v in enumerate(vals):
|
|
139
|
+
if v >= 10.0:
|
|
140
|
+
ax_state.text(
|
|
141
|
+
left_acc[idx] + v / 2.0,
|
|
142
|
+
ys[idx],
|
|
143
|
+
f"{v:.0f}%",
|
|
144
|
+
ha="center",
|
|
145
|
+
va="center",
|
|
146
|
+
fontsize=cfg.theme.caption_size - 0.5,
|
|
147
|
+
fontweight="bold",
|
|
148
|
+
color=_contrast_text(col),
|
|
149
|
+
zorder=4,
|
|
150
|
+
)
|
|
151
|
+
left_acc += vals
|
|
152
|
+
|
|
153
|
+
y_labels = [f"{resolve_label(g, cfg)} (n={int(state_ct.loc[g].sum())})" for g in groups]
|
|
154
|
+
ax_state.set_yticks(ys)
|
|
155
|
+
ax_state.set_yticklabels(y_labels, fontsize=cfg.theme.tick_size, fontweight="bold")
|
|
156
|
+
ax_state.set_xlim(0, 100)
|
|
157
|
+
style_axes(ax_state, title="Current State", xlabel=state_xlabel, config=cfg)
|
|
158
|
+
ax_state.yaxis.grid(False)
|
|
159
|
+
ax_state.legend(
|
|
160
|
+
loc="upper center",
|
|
161
|
+
bbox_to_anchor=(0.5, -0.15),
|
|
162
|
+
ncol=min(len(bands), 6),
|
|
163
|
+
frameon=False,
|
|
164
|
+
fontsize=cfg.theme.legend_size - 0.5,
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
# Right panel: Diverging Trend bar around 0%
|
|
168
|
+
trend_ct = pd.crosstab(work["_grp"], work["_trend"]).reindex(
|
|
169
|
+
index=groups, columns=["Degrading", "Indeterminate", "Improving"], fill_value=0
|
|
170
|
+
)
|
|
171
|
+
trend_totals = trend_ct.sum(axis=1).replace(0, 1)
|
|
172
|
+
trend_pct = trend_ct.div(trend_totals, axis=0) * 100.0
|
|
173
|
+
|
|
174
|
+
deg = trend_pct["Degrading"].to_numpy(dtype=float)
|
|
175
|
+
ind = trend_pct["Indeterminate"].to_numpy(dtype=float)
|
|
176
|
+
imp = trend_pct["Improving"].to_numpy(dtype=float)
|
|
177
|
+
|
|
178
|
+
c_deg = t_pal.get("Degrading", "#ff6666")
|
|
179
|
+
c_ind = t_pal.get("Indeterminate", "#e6e600")
|
|
180
|
+
c_imp = t_pal.get("Improving", "#29b6f6")
|
|
181
|
+
|
|
182
|
+
# Center Indeterminate around 0, Degrading left, Improving right
|
|
183
|
+
ax_trend.barh(
|
|
184
|
+
ys,
|
|
185
|
+
-ind / 2.0,
|
|
186
|
+
left=0.0,
|
|
187
|
+
height=0.62,
|
|
188
|
+
color=c_ind,
|
|
189
|
+
edgecolor="#ffffff",
|
|
190
|
+
linewidth=0.6,
|
|
191
|
+
label="Indeterminate",
|
|
192
|
+
zorder=3,
|
|
193
|
+
)
|
|
194
|
+
ax_trend.barh(
|
|
195
|
+
ys,
|
|
196
|
+
ind / 2.0,
|
|
197
|
+
left=0.0,
|
|
198
|
+
height=0.62,
|
|
199
|
+
color=c_ind,
|
|
200
|
+
edgecolor="#ffffff",
|
|
201
|
+
linewidth=0.6,
|
|
202
|
+
zorder=3,
|
|
203
|
+
)
|
|
204
|
+
ax_trend.barh(
|
|
205
|
+
ys,
|
|
206
|
+
-deg,
|
|
207
|
+
left=-ind / 2.0,
|
|
208
|
+
height=0.62,
|
|
209
|
+
color=c_deg,
|
|
210
|
+
edgecolor="#ffffff",
|
|
211
|
+
linewidth=0.8,
|
|
212
|
+
label="Degrading",
|
|
213
|
+
zorder=3,
|
|
214
|
+
)
|
|
215
|
+
ax_trend.barh(
|
|
216
|
+
ys,
|
|
217
|
+
imp,
|
|
218
|
+
left=ind / 2.0,
|
|
219
|
+
height=0.62,
|
|
220
|
+
color=c_imp,
|
|
221
|
+
edgecolor="#ffffff",
|
|
222
|
+
linewidth=0.8,
|
|
223
|
+
label="Improving",
|
|
224
|
+
zorder=3,
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
for idx in range(n_grp):
|
|
228
|
+
if deg[idx] >= 10.0:
|
|
229
|
+
ax_trend.text(
|
|
230
|
+
-(ind[idx] / 2.0 + deg[idx] / 2.0),
|
|
231
|
+
ys[idx],
|
|
232
|
+
f"{deg[idx]:.0f}%",
|
|
233
|
+
ha="center",
|
|
234
|
+
va="center",
|
|
235
|
+
fontsize=cfg.theme.caption_size - 0.5,
|
|
236
|
+
fontweight="bold",
|
|
237
|
+
color=_contrast_text(c_deg),
|
|
238
|
+
zorder=4,
|
|
239
|
+
)
|
|
240
|
+
if imp[idx] >= 10.0:
|
|
241
|
+
ax_trend.text(
|
|
242
|
+
ind[idx] / 2.0 + imp[idx] / 2.0,
|
|
243
|
+
ys[idx],
|
|
244
|
+
f"{imp[idx]:.0f}%",
|
|
245
|
+
ha="center",
|
|
246
|
+
va="center",
|
|
247
|
+
fontsize=cfg.theme.caption_size - 0.5,
|
|
248
|
+
fontweight="bold",
|
|
249
|
+
color=_contrast_text(c_imp),
|
|
250
|
+
zorder=4,
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
ax_trend.axvline(0, color=cfg.theme.text_color, linewidth=1.2, zorder=4)
|
|
254
|
+
max_ext = max(float(np.max(ind / 2.0 + deg)), float(np.max(ind / 2.0 + imp)), 50.0)
|
|
255
|
+
lim = min(100.0, np.ceil(max_ext / 10.0) * 10.0 + 5.0)
|
|
256
|
+
ax_trend.set_xlim(-lim, lim)
|
|
257
|
+
ticks = ax_trend.get_xticks()
|
|
258
|
+
ax_trend.set_xticks([t for t in ticks if -lim <= t <= lim])
|
|
259
|
+
ax_trend.set_xticklabels([f"{abs(t):.0f}%" for t in ax_trend.get_xticks()])
|
|
260
|
+
ax_trend.tick_params(axis="y", length=0)
|
|
261
|
+
style_axes(ax_trend, title="Trend Direction", xlabel=trend_xlabel, config=cfg)
|
|
262
|
+
ax_trend.yaxis.grid(False)
|
|
263
|
+
ax_trend.legend(
|
|
264
|
+
loc="upper center",
|
|
265
|
+
bbox_to_anchor=(0.5, -0.15),
|
|
266
|
+
ncol=3,
|
|
267
|
+
frameon=False,
|
|
268
|
+
fontsize=cfg.theme.legend_size - 0.5,
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
fig.suptitle(
|
|
272
|
+
title,
|
|
273
|
+
fontsize=cfg.theme.title_size + 1.5,
|
|
274
|
+
fontweight=cfg.theme.title_weight,
|
|
275
|
+
color=cfg.theme.text_color,
|
|
276
|
+
y=0.98,
|
|
277
|
+
)
|
|
278
|
+
if subtitle:
|
|
279
|
+
fig.text(
|
|
280
|
+
0.5,
|
|
281
|
+
0.92,
|
|
282
|
+
subtitle,
|
|
283
|
+
ha="center",
|
|
284
|
+
va="top",
|
|
285
|
+
fontsize=cfg.theme.subtitle_size,
|
|
286
|
+
color=cfg.theme.caption_color,
|
|
287
|
+
)
|
|
288
|
+
fig.subplots_adjust(
|
|
289
|
+
top=0.82 if subtitle else 0.87,
|
|
290
|
+
bottom=0.20,
|
|
291
|
+
left=0.22,
|
|
292
|
+
right=0.97,
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
return fig, (ax_state, ax_trend)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def state_trend_lollipop(
|
|
299
|
+
df: pd.DataFrame,
|
|
300
|
+
*,
|
|
301
|
+
site_col: str | None = None,
|
|
302
|
+
value_col: str | None = None,
|
|
303
|
+
band_col: str | None = None,
|
|
304
|
+
slope_col: str | None = None,
|
|
305
|
+
trend_col: str | None = None,
|
|
306
|
+
horizon_years: float = 5.0,
|
|
307
|
+
indicator: str | None = None,
|
|
308
|
+
indicator_directions: dict[str, str] | None = None,
|
|
309
|
+
lower_is_better: bool | None = None,
|
|
310
|
+
thresholds: list[tuple[str, float, float]] | None = None,
|
|
311
|
+
nbl_value: float | None = None,
|
|
312
|
+
nbl_label: str = "National Bottom Line",
|
|
313
|
+
palette: dict[str, str] | None = None,
|
|
314
|
+
trend_palette: dict[str, str] | None = None,
|
|
315
|
+
title: str = "Site State & 5-Year Trend Trajectory",
|
|
316
|
+
subtitle: str | None = None,
|
|
317
|
+
xlabel: str = "Current Median (arrow tip = projected 5-yr trajectory)",
|
|
318
|
+
ylabel: str = "",
|
|
319
|
+
figsize: tuple[float, float] | None = None,
|
|
320
|
+
ax: Axes | None = None,
|
|
321
|
+
config: str | Path | Config | None = None,
|
|
322
|
+
) -> tuple[Figure, Axes]:
|
|
323
|
+
"""Plot sites ranked by current State value with directional trend velocity arrows.
|
|
324
|
+
|
|
325
|
+
Each site dot sits at its current 5-year median colored by ``NOF_Grade``, while an
|
|
326
|
+
arrow extends to ``value * (1 + pct_annual_change / 100 * horizon_years)`` so readers
|
|
327
|
+
immediately see both current state and trajectory toward/away from band thresholds.
|
|
328
|
+
|
|
329
|
+
When ``lower_is_better`` is ``None`` and no ``trend_col`` is present, polarity is
|
|
330
|
+
resolved automatically from ``indicator`` (or a single unique value in
|
|
331
|
+
``config.columns["indicator"]``) via ``indicator_directions`` /
|
|
332
|
+
``config.indicator_directions``.
|
|
333
|
+
|
|
334
|
+
Returns:
|
|
335
|
+
Tuple of ``(fig, ax)``.
|
|
336
|
+
"""
|
|
337
|
+
from stplot.config import is_lower_better
|
|
338
|
+
|
|
339
|
+
cfg = ensure_config(config)
|
|
340
|
+
r_site = resolve_column(site_col, cfg, "site_id")
|
|
341
|
+
r_val = resolve_column(value_col, cfg, "state_value")
|
|
342
|
+
r_band = resolve_column(band_col, cfg, "state_band")
|
|
343
|
+
r_slope = resolve_column(slope_col, cfg, "pct_annual_change")
|
|
344
|
+
validate_columns(df, [r_site, r_val, r_band, r_slope], context="state_trend_lollipop")
|
|
345
|
+
|
|
346
|
+
work = df.copy()
|
|
347
|
+
work["_val"] = pd.to_numeric(work[r_val], errors="coerce")
|
|
348
|
+
work["_slope"] = pd.to_numeric(work[r_slope], errors="coerce").fillna(0.0)
|
|
349
|
+
work = work.dropna(subset=["_val"]).sort_values("_val", ascending=True).reset_index(drop=True)
|
|
350
|
+
if work.empty:
|
|
351
|
+
raise ValueError("state_trend_lollipop: No valid numeric rows to plot.")
|
|
352
|
+
|
|
353
|
+
inferred_ind = indicator
|
|
354
|
+
if inferred_ind is None:
|
|
355
|
+
ind_col = cfg.columns.get("indicator")
|
|
356
|
+
if ind_col and ind_col in work.columns:
|
|
357
|
+
uniq = work[ind_col].dropna().astype(str).unique()
|
|
358
|
+
if len(uniq) == 1:
|
|
359
|
+
inferred_ind = str(uniq[0])
|
|
360
|
+
resolved_lower_better = is_lower_better(
|
|
361
|
+
inferred_ind,
|
|
362
|
+
cfg,
|
|
363
|
+
lower_is_better=lower_is_better,
|
|
364
|
+
overrides=indicator_directions,
|
|
365
|
+
default=True,
|
|
366
|
+
)
|
|
367
|
+
|
|
368
|
+
r_trend = resolve_column(trend_col, cfg, "trend_direction")
|
|
369
|
+
if r_trend in work.columns:
|
|
370
|
+
work["_trend"] = _normalize_trend_3level(work, r_trend, cfg)
|
|
371
|
+
else:
|
|
372
|
+
work["_trend"] = np.where(
|
|
373
|
+
np.abs(work["_slope"]) < 0.5,
|
|
374
|
+
"Indeterminate",
|
|
375
|
+
np.where(
|
|
376
|
+
(work["_slope"] < 0) if resolved_lower_better else (work["_slope"] > 0),
|
|
377
|
+
"Improving",
|
|
378
|
+
"Degrading",
|
|
379
|
+
),
|
|
380
|
+
)
|
|
381
|
+
|
|
382
|
+
s_pal = resolve_palette(palette, cfg, "state_bands")
|
|
383
|
+
t_pal = resolve_palette(trend_palette, cfg, "trend_directions")
|
|
384
|
+
|
|
385
|
+
n = len(work)
|
|
386
|
+
ys = np.arange(n)
|
|
387
|
+
|
|
388
|
+
vals = work["_val"].to_numpy(dtype=float)
|
|
389
|
+
slopes = work["_slope"].to_numpy(dtype=float)
|
|
390
|
+
projected = np.maximum(0.0, vals * (1.0 + (slopes / 100.0) * horizon_years))
|
|
391
|
+
xmax = float(max(np.max(vals), np.max(projected))) * 1.18
|
|
392
|
+
if thresholds:
|
|
393
|
+
xmax = max(xmax, max(high for _, _, high in thresholds) * 1.05)
|
|
394
|
+
|
|
395
|
+
with mpl_theme(cfg):
|
|
396
|
+
if ax is None:
|
|
397
|
+
fig_h = max(4.4, 0.48 * n + 1.9)
|
|
398
|
+
fig, ax = plt.subplots(figsize=figsize or (11.2, fig_h))
|
|
399
|
+
else:
|
|
400
|
+
fig = ax.figure # type: ignore[assignment]
|
|
401
|
+
|
|
402
|
+
# Vertical NOF Band zones
|
|
403
|
+
if thresholds:
|
|
404
|
+
for band_name, low, high in thresholds:
|
|
405
|
+
b_col = s_pal.get(band_name, "#e0e0e0")
|
|
406
|
+
ax.axvspan(low, high, facecolor=b_col, alpha=0.14, zorder=0)
|
|
407
|
+
ax.text(
|
|
408
|
+
(low + high) / 2.0,
|
|
409
|
+
n - 0.35,
|
|
410
|
+
f"Band {band_name}",
|
|
411
|
+
ha="center",
|
|
412
|
+
va="bottom",
|
|
413
|
+
fontsize=cfg.theme.caption_size - 0.5,
|
|
414
|
+
fontweight="bold",
|
|
415
|
+
color=cfg.theme.caption_color,
|
|
416
|
+
zorder=1,
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
if nbl_value is not None:
|
|
420
|
+
ax.axvline(nbl_value, color="#c62828", linestyle="--", linewidth=1.6, zorder=2)
|
|
421
|
+
ax.text(
|
|
422
|
+
nbl_value,
|
|
423
|
+
-0.58,
|
|
424
|
+
f" {nbl_label}",
|
|
425
|
+
ha="left",
|
|
426
|
+
va="bottom",
|
|
427
|
+
fontsize=cfg.theme.caption_size - 0.5,
|
|
428
|
+
fontweight="bold",
|
|
429
|
+
color="#c62828",
|
|
430
|
+
zorder=4,
|
|
431
|
+
)
|
|
432
|
+
|
|
433
|
+
for i, row in work.iterrows():
|
|
434
|
+
y = ys[i]
|
|
435
|
+
v = vals[i]
|
|
436
|
+
p = projected[i]
|
|
437
|
+
sl = slopes[i]
|
|
438
|
+
band = str(row[r_band])
|
|
439
|
+
tr = str(row["_trend"])
|
|
440
|
+
dot_col = s_pal.get(band, cfg.theme.accent_color)
|
|
441
|
+
arr_col = (
|
|
442
|
+
t_pal.get("Improving", "#1976d2")
|
|
443
|
+
if tr == "Improving"
|
|
444
|
+
else (t_pal.get("Degrading", "#d32f2f") if tr == "Degrading" else "#64748b")
|
|
445
|
+
)
|
|
446
|
+
|
|
447
|
+
# Subtle lollipop stem from 0 to current state
|
|
448
|
+
ax.plot([0, v], [y, y], color="#cbd5e1", linewidth=1.6, zorder=2)
|
|
449
|
+
|
|
450
|
+
# Velocity arrow from current state to projected value
|
|
451
|
+
if abs(p - v) > xmax * 0.008:
|
|
452
|
+
ax.annotate(
|
|
453
|
+
"",
|
|
454
|
+
xy=(p, y),
|
|
455
|
+
xytext=(v, y),
|
|
456
|
+
arrowprops={
|
|
457
|
+
"arrowstyle": "-|>,head_length=0.55,head_width=0.32",
|
|
458
|
+
"color": arr_col,
|
|
459
|
+
"lw": 2.4,
|
|
460
|
+
},
|
|
461
|
+
zorder=4,
|
|
462
|
+
)
|
|
463
|
+
|
|
464
|
+
# Current state dot
|
|
465
|
+
ax.scatter(
|
|
466
|
+
[v],
|
|
467
|
+
[y],
|
|
468
|
+
s=135,
|
|
469
|
+
color=dot_col,
|
|
470
|
+
edgecolors="#1e2a38",
|
|
471
|
+
linewidths=1.0,
|
|
472
|
+
zorder=5,
|
|
473
|
+
)
|
|
474
|
+
ax.text(
|
|
475
|
+
v,
|
|
476
|
+
y,
|
|
477
|
+
band[:1],
|
|
478
|
+
ha="center",
|
|
479
|
+
va="center",
|
|
480
|
+
fontsize=7.5,
|
|
481
|
+
fontweight="bold",
|
|
482
|
+
color=_contrast_text(dot_col),
|
|
483
|
+
zorder=6,
|
|
484
|
+
)
|
|
485
|
+
|
|
486
|
+
# Right-hand %/yr readout
|
|
487
|
+
ax.text(
|
|
488
|
+
xmax * 1.01,
|
|
489
|
+
y,
|
|
490
|
+
f"{sl:+.1f}%/yr",
|
|
491
|
+
ha="left",
|
|
492
|
+
va="center",
|
|
493
|
+
fontsize=cfg.theme.caption_size,
|
|
494
|
+
fontweight="bold",
|
|
495
|
+
color=arr_col,
|
|
496
|
+
)
|
|
497
|
+
|
|
498
|
+
ax.set_yticks(ys)
|
|
499
|
+
ax.set_yticklabels(
|
|
500
|
+
work[r_site].astype(str).tolist(),
|
|
501
|
+
fontsize=cfg.theme.tick_size,
|
|
502
|
+
fontweight="bold",
|
|
503
|
+
)
|
|
504
|
+
ax.set_xlim(0, xmax * 1.15)
|
|
505
|
+
ax.set_ylim(-0.7, n + 0.15)
|
|
506
|
+
|
|
507
|
+
legend_handles = [
|
|
508
|
+
plt.Line2D(
|
|
509
|
+
[0], [0], color=t_pal.get("Improving", "#29b6f6"), lw=2.5, label="Improving arrow"
|
|
510
|
+
),
|
|
511
|
+
plt.Line2D(
|
|
512
|
+
[0], [0], color=t_pal.get("Degrading", "#ff6666"), lw=2.5, label="Degrading arrow"
|
|
513
|
+
),
|
|
514
|
+
plt.Line2D([0], [0], color="#64748b", lw=2.0, label="Indeterminate"),
|
|
515
|
+
]
|
|
516
|
+
ax.legend(
|
|
517
|
+
handles=legend_handles,
|
|
518
|
+
loc="upper center",
|
|
519
|
+
bbox_to_anchor=(0.5, -0.13),
|
|
520
|
+
ncol=3,
|
|
521
|
+
frameon=False,
|
|
522
|
+
fontsize=cfg.theme.legend_size - 0.5,
|
|
523
|
+
)
|
|
524
|
+
|
|
525
|
+
style_axes(ax, title=None, xlabel=xlabel, ylabel=ylabel, config=cfg)
|
|
526
|
+
ax.yaxis.grid(False)
|
|
527
|
+
fig.suptitle(
|
|
528
|
+
title,
|
|
529
|
+
fontsize=cfg.theme.title_size + 1,
|
|
530
|
+
fontweight=cfg.theme.title_weight,
|
|
531
|
+
color=cfg.theme.text_color,
|
|
532
|
+
y=0.98,
|
|
533
|
+
)
|
|
534
|
+
if subtitle:
|
|
535
|
+
fig.text(
|
|
536
|
+
0.5,
|
|
537
|
+
0.92,
|
|
538
|
+
subtitle,
|
|
539
|
+
ha="center",
|
|
540
|
+
va="top",
|
|
541
|
+
fontsize=cfg.theme.subtitle_size,
|
|
542
|
+
color=cfg.theme.caption_color,
|
|
543
|
+
)
|
|
544
|
+
fig.tight_layout(rect=(0.0, 0.03, 1.0, 0.89 if subtitle else 0.94))
|
|
545
|
+
|
|
546
|
+
return fig, ax
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def state_trend_map(
|
|
550
|
+
sites_df: pd.DataFrame,
|
|
551
|
+
*,
|
|
552
|
+
zones_gdf: Any | None = None,
|
|
553
|
+
x_col: str | None = None,
|
|
554
|
+
y_col: str | None = None,
|
|
555
|
+
band_col: str | None = None,
|
|
556
|
+
trend_col: str | None = None,
|
|
557
|
+
magnitude_col: str | None = None,
|
|
558
|
+
crs: str | None = None,
|
|
559
|
+
state_palette: dict[str, str] | None = None,
|
|
560
|
+
state_palette_name: str = "state_bands",
|
|
561
|
+
title: str = "Regional State & Trends Map",
|
|
562
|
+
subtitle: str | None = None,
|
|
563
|
+
figsize: tuple[float, float] = (9.6, 8.2),
|
|
564
|
+
ax: Axes | None = None,
|
|
565
|
+
config: str | Path | Config | None = None,
|
|
566
|
+
) -> tuple[Figure, Axes]:
|
|
567
|
+
"""Render a single static publication map encoding both State (color) and Trend (shape).
|
|
568
|
+
|
|
569
|
+
Each monitoring site marker uses:
|
|
570
|
+
- **Fill color** = Current State (``NOF_Grade`` A–E or One Plan Pass/Fail)
|
|
571
|
+
- **Marker shape** = Trend Direction (``▲`` Improving, ``●`` Indeterminate,
|
|
572
|
+
``▼`` Degrading, ``■`` Not Analysed)
|
|
573
|
+
- **Optional size** = scaled by ``|magnitude_col|`` (e.g., ``Percent.annual.change``)
|
|
574
|
+
|
|
575
|
+
Requires the ``geo`` optional extra (``pip install "stplot[geo]"``).
|
|
576
|
+
|
|
577
|
+
Returns:
|
|
578
|
+
Tuple of ``(fig, ax)``.
|
|
579
|
+
"""
|
|
580
|
+
try:
|
|
581
|
+
import geopandas as gpd
|
|
582
|
+
except ImportError as exc:
|
|
583
|
+
raise ImportError(
|
|
584
|
+
'geopandas is required for state_trend_map(). Install with: pip install "stplot[geo]"'
|
|
585
|
+
) from exc
|
|
586
|
+
|
|
587
|
+
cfg = ensure_config(config)
|
|
588
|
+
r_band = resolve_column(band_col, cfg, "state_band")
|
|
589
|
+
r_trend = resolve_column(trend_col, cfg, "trend_direction")
|
|
590
|
+
|
|
591
|
+
if isinstance(sites_df, gpd.GeoDataFrame):
|
|
592
|
+
gdf = sites_df.copy()
|
|
593
|
+
validate_columns(gdf, [r_band, r_trend], context="state_trend_map")
|
|
594
|
+
else:
|
|
595
|
+
r_x = resolve_column(x_col, cfg, "x")
|
|
596
|
+
r_y = resolve_column(y_col, cfg, "y")
|
|
597
|
+
validate_columns(sites_df, [r_x, r_y, r_band, r_trend], context="state_trend_map")
|
|
598
|
+
src_crs = crs or cfg.columns.get("crs", "EPSG:2193")
|
|
599
|
+
gdf = gpd.GeoDataFrame(
|
|
600
|
+
sites_df.copy(),
|
|
601
|
+
geometry=gpd.points_from_xy(sites_df[r_x], sites_df[r_y]),
|
|
602
|
+
crs=src_crs,
|
|
603
|
+
)
|
|
604
|
+
|
|
605
|
+
if gdf.empty:
|
|
606
|
+
raise ValueError("state_trend_map: Input sites DataFrame is empty.")
|
|
607
|
+
|
|
608
|
+
gdf["_trend"] = _normalize_trend_3level(gdf, r_trend, cfg)
|
|
609
|
+
s_pal = resolve_palette(state_palette, cfg, state_palette_name)
|
|
610
|
+
|
|
611
|
+
zones_plot = None
|
|
612
|
+
if zones_gdf is not None:
|
|
613
|
+
zones_plot = zones_gdf.copy()
|
|
614
|
+
if gdf.crs is not None and zones_plot.crs is not None and zones_plot.crs != gdf.crs:
|
|
615
|
+
zones_plot = zones_plot.to_crs(gdf.crs)
|
|
616
|
+
|
|
617
|
+
marker_map = {
|
|
618
|
+
"Improving": ("^", "Improving (▲)"),
|
|
619
|
+
"Indeterminate": ("o", "Indeterminate (●)"),
|
|
620
|
+
"Degrading": ("v", "Degrading (▼)"),
|
|
621
|
+
"Not Analysed": ("s", "Not Analysed (■)"),
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
with mpl_theme(cfg):
|
|
625
|
+
if ax is None:
|
|
626
|
+
fig, ax = plt.subplots(figsize=figsize)
|
|
627
|
+
else:
|
|
628
|
+
fig = ax.figure # type: ignore[assignment]
|
|
629
|
+
|
|
630
|
+
ax.set_facecolor("#eef3f7")
|
|
631
|
+
|
|
632
|
+
if zones_plot is not None:
|
|
633
|
+
zones_plot.plot(
|
|
634
|
+
ax=ax,
|
|
635
|
+
facecolor="#ffffff",
|
|
636
|
+
edgecolor="#94a3b8",
|
|
637
|
+
linewidth=1.0,
|
|
638
|
+
zorder=1,
|
|
639
|
+
)
|
|
640
|
+
|
|
641
|
+
if magnitude_col and magnitude_col in gdf.columns:
|
|
642
|
+
mags = pd.to_numeric(gdf[magnitude_col], errors="coerce").abs().fillna(1.0)
|
|
643
|
+
m_max = max(float(mags.max()), 1.0)
|
|
644
|
+
sizes = 85.0 + 180.0 * (mags / m_max)
|
|
645
|
+
else:
|
|
646
|
+
sizes = pd.Series(135.0, index=gdf.index)
|
|
647
|
+
|
|
648
|
+
gdf["_size"] = sizes
|
|
649
|
+
present_bands: set[str] = set()
|
|
650
|
+
present_trends: list[str] = []
|
|
651
|
+
|
|
652
|
+
for tr_key, (mk, _) in marker_map.items():
|
|
653
|
+
sub = gdf[gdf["_trend"] == tr_key]
|
|
654
|
+
if sub.empty:
|
|
655
|
+
continue
|
|
656
|
+
present_trends.append(tr_key)
|
|
657
|
+
bands_sub = sub[r_band].astype(str).tolist()
|
|
658
|
+
present_bands.update(bands_sub)
|
|
659
|
+
colors = [s_pal.get(b, "#bdbdbd") for b in bands_sub]
|
|
660
|
+
ax.scatter(
|
|
661
|
+
sub.geometry.x,
|
|
662
|
+
sub.geometry.y,
|
|
663
|
+
s=sub["_size"],
|
|
664
|
+
c=colors,
|
|
665
|
+
marker=mk,
|
|
666
|
+
edgecolors="#1e2a38",
|
|
667
|
+
linewidths=0.95,
|
|
668
|
+
alpha=0.94,
|
|
669
|
+
zorder=4,
|
|
670
|
+
)
|
|
671
|
+
|
|
672
|
+
ax.set_aspect("equal")
|
|
673
|
+
ax.set_xticks([])
|
|
674
|
+
ax.set_yticks([])
|
|
675
|
+
for spine in ax.spines.values():
|
|
676
|
+
spine.set_edgecolor("#cbd5e1")
|
|
677
|
+
spine.set_linewidth(1.0)
|
|
678
|
+
|
|
679
|
+
# Crisp North arrow in top-left
|
|
680
|
+
ax.annotate(
|
|
681
|
+
"N",
|
|
682
|
+
xy=(0.055, 0.94),
|
|
683
|
+
xytext=(0.055, 0.84),
|
|
684
|
+
xycoords="axes fraction",
|
|
685
|
+
textcoords="axes fraction",
|
|
686
|
+
ha="center",
|
|
687
|
+
va="center",
|
|
688
|
+
fontsize=11,
|
|
689
|
+
fontweight="bold",
|
|
690
|
+
color="#1e2a38",
|
|
691
|
+
arrowprops={"arrowstyle": "-|>", "color": "#1e2a38", "lw": 1.8},
|
|
692
|
+
zorder=6,
|
|
693
|
+
)
|
|
694
|
+
|
|
695
|
+
# Dual legend: State Band colors + Trend shapes
|
|
696
|
+
order = resolve_category_order(None, cfg, state_palette_name)
|
|
697
|
+
ordered_bands = [b for b in order if b in present_bands] + [
|
|
698
|
+
b for b in sorted(present_bands) if b not in order
|
|
699
|
+
]
|
|
700
|
+
state_handles = [
|
|
701
|
+
plt.Line2D(
|
|
702
|
+
[0],
|
|
703
|
+
[0],
|
|
704
|
+
marker="o",
|
|
705
|
+
color="none",
|
|
706
|
+
markerfacecolor=s_pal.get(b, "#bdbdbd"),
|
|
707
|
+
markeredgecolor="#1e2a38",
|
|
708
|
+
markersize=9,
|
|
709
|
+
label=f"Band {b}" if len(b) == 1 else b,
|
|
710
|
+
)
|
|
711
|
+
for b in ordered_bands
|
|
712
|
+
]
|
|
713
|
+
trend_handles = [
|
|
714
|
+
plt.Line2D(
|
|
715
|
+
[0],
|
|
716
|
+
[0],
|
|
717
|
+
marker=marker_map[t][0],
|
|
718
|
+
color="none",
|
|
719
|
+
markerfacecolor="#475569",
|
|
720
|
+
markeredgecolor="#1e2a38",
|
|
721
|
+
markersize=9,
|
|
722
|
+
label=marker_map[t][1],
|
|
723
|
+
)
|
|
724
|
+
for t in present_trends
|
|
725
|
+
]
|
|
726
|
+
|
|
727
|
+
leg1 = ax.legend(
|
|
728
|
+
handles=state_handles,
|
|
729
|
+
title="Current State",
|
|
730
|
+
loc="upper left",
|
|
731
|
+
bbox_to_anchor=(1.02, 1.0),
|
|
732
|
+
frameon=True,
|
|
733
|
+
facecolor="#ffffff",
|
|
734
|
+
edgecolor="#d7e0ea",
|
|
735
|
+
fontsize=cfg.theme.legend_size,
|
|
736
|
+
title_fontsize=cfg.theme.legend_size,
|
|
737
|
+
)
|
|
738
|
+
ax.add_artist(leg1)
|
|
739
|
+
ax.legend(
|
|
740
|
+
handles=trend_handles,
|
|
741
|
+
title="Trend Direction",
|
|
742
|
+
loc="upper left",
|
|
743
|
+
bbox_to_anchor=(1.02, 0.56),
|
|
744
|
+
frameon=True,
|
|
745
|
+
facecolor="#ffffff",
|
|
746
|
+
edgecolor="#d7e0ea",
|
|
747
|
+
fontsize=cfg.theme.legend_size,
|
|
748
|
+
title_fontsize=cfg.theme.legend_size,
|
|
749
|
+
)
|
|
750
|
+
|
|
751
|
+
fig.suptitle(
|
|
752
|
+
title,
|
|
753
|
+
fontsize=cfg.theme.title_size + 1,
|
|
754
|
+
fontweight=cfg.theme.title_weight,
|
|
755
|
+
color=cfg.theme.text_color,
|
|
756
|
+
y=0.97,
|
|
757
|
+
)
|
|
758
|
+
if subtitle:
|
|
759
|
+
fig.text(
|
|
760
|
+
0.5,
|
|
761
|
+
0.92,
|
|
762
|
+
subtitle,
|
|
763
|
+
ha="center",
|
|
764
|
+
va="top",
|
|
765
|
+
fontsize=cfg.theme.subtitle_size,
|
|
766
|
+
color=cfg.theme.caption_color,
|
|
767
|
+
)
|
|
768
|
+
fig.subplots_adjust(right=0.77, top=0.87 if subtitle else 0.91, bottom=0.05)
|
|
769
|
+
|
|
770
|
+
return fig, ax
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
def state_trend_risk_matrix(
|
|
774
|
+
df: pd.DataFrame,
|
|
775
|
+
*,
|
|
776
|
+
band_col: str | None = None,
|
|
777
|
+
trend_col: str | None = None,
|
|
778
|
+
band_order: list[str] | None = None,
|
|
779
|
+
title: str = "State × Trend Management Risk Matrix",
|
|
780
|
+
subtitle: str | None = None,
|
|
781
|
+
figsize: tuple[float, float] = (8.8, 6.4),
|
|
782
|
+
ax: Axes | None = None,
|
|
783
|
+
config: str | Path | Config | None = None,
|
|
784
|
+
) -> tuple[Figure, Axes]:
|
|
785
|
+
"""Render a 2D State Band × Trend Direction contingency matrix highlighting priority hotspots.
|
|
786
|
+
|
|
787
|
+
Rows display current State Bands (``A``–``E``) and columns display Trend Direction
|
|
788
|
+
(``Degrading`` / ``Indeterminate`` / ``Improving``), with site counts, percentages,
|
|
789
|
+
row/column totals, and risk-priority shading (highlighting the bottom-left ``D/E + Degrading``
|
|
790
|
+
urgent action corner).
|
|
791
|
+
|
|
792
|
+
Returns:
|
|
793
|
+
Tuple of ``(fig, ax)``.
|
|
794
|
+
"""
|
|
795
|
+
cfg = ensure_config(config)
|
|
796
|
+
r_band = resolve_column(band_col, cfg, "state_band")
|
|
797
|
+
r_trend = resolve_column(trend_col, cfg, "trend_direction")
|
|
798
|
+
validate_columns(df, [r_band, r_trend], context="state_trend_risk_matrix")
|
|
799
|
+
|
|
800
|
+
work = df.copy()
|
|
801
|
+
if work.empty:
|
|
802
|
+
raise ValueError("state_trend_risk_matrix: Input DataFrame is empty.")
|
|
803
|
+
|
|
804
|
+
work["_band"] = work[r_band].astype(str)
|
|
805
|
+
work["_trend"] = _normalize_trend_3level(work, r_trend, cfg)
|
|
806
|
+
|
|
807
|
+
trend_cols = ["Degrading", "Indeterminate", "Improving"]
|
|
808
|
+
bands_present = list(dict.fromkeys(work["_band"].tolist()))
|
|
809
|
+
cfg_bands = resolve_category_order(band_order, cfg, "state_bands")
|
|
810
|
+
bands = [b for b in cfg_bands if b in bands_present and b != "Not assessed"]
|
|
811
|
+
if not bands:
|
|
812
|
+
bands = bands_present
|
|
813
|
+
|
|
814
|
+
ct = pd.crosstab(work["_band"], work["_trend"]).reindex(
|
|
815
|
+
index=bands, columns=trend_cols, fill_value=0
|
|
816
|
+
)
|
|
817
|
+
total_sites = int(ct.to_numpy().sum())
|
|
818
|
+
if total_sites == 0:
|
|
819
|
+
raise ValueError("state_trend_risk_matrix: No valid State × Trend combinations found.")
|
|
820
|
+
|
|
821
|
+
n_rows = len(bands)
|
|
822
|
+
n_cols = len(trend_cols)
|
|
823
|
+
state_pal = resolve_palette(None, cfg, "state_bands")
|
|
824
|
+
|
|
825
|
+
with mpl_theme(cfg):
|
|
826
|
+
if ax is None:
|
|
827
|
+
fig, ax = plt.subplots(figsize=figsize)
|
|
828
|
+
else:
|
|
829
|
+
fig = ax.figure # type: ignore[assignment]
|
|
830
|
+
|
|
831
|
+
ax.set_facecolor(cfg.theme.background_color)
|
|
832
|
+
|
|
833
|
+
for r_idx, band in enumerate(bands):
|
|
834
|
+
y = n_rows - 1 - r_idx
|
|
835
|
+
# Risk score: 0 (top-right: good & improving) -> 1 (bottom-left: poor & degrading)
|
|
836
|
+
band_risk = r_idx / max(n_rows - 1, 1)
|
|
837
|
+
for c_idx, tr in enumerate(trend_cols):
|
|
838
|
+
trend_risk = (n_cols - 1 - c_idx) / max(n_cols - 1, 1)
|
|
839
|
+
risk = 0.60 * band_risk + 0.40 * trend_risk
|
|
840
|
+
count = int(ct.loc[band, tr])
|
|
841
|
+
pct = 100.0 * count / total_sites
|
|
842
|
+
|
|
843
|
+
if risk >= 0.72:
|
|
844
|
+
fill, edge, lw = "#fde2e2", "#d32f2f", 2.0
|
|
845
|
+
elif risk >= 0.48:
|
|
846
|
+
fill, edge, lw = "#fef3c7", "#d97706", 1.1
|
|
847
|
+
elif risk <= 0.25:
|
|
848
|
+
fill, edge, lw = "#dcfce7", "#2e7d32", 1.3
|
|
849
|
+
else:
|
|
850
|
+
fill, edge, lw = "#f1f5f9", "#cbd5e1", 1.0
|
|
851
|
+
|
|
852
|
+
ax.add_patch(
|
|
853
|
+
FancyBboxPatch(
|
|
854
|
+
(c_idx + 0.06, y + 0.08),
|
|
855
|
+
0.88,
|
|
856
|
+
0.84,
|
|
857
|
+
boxstyle="round,pad=0.02,rounding_size=0.10",
|
|
858
|
+
facecolor=fill,
|
|
859
|
+
edgecolor=edge,
|
|
860
|
+
linewidth=lw,
|
|
861
|
+
zorder=2,
|
|
862
|
+
)
|
|
863
|
+
)
|
|
864
|
+
ax.text(
|
|
865
|
+
c_idx + 0.5,
|
|
866
|
+
y + 0.58,
|
|
867
|
+
f"{count}",
|
|
868
|
+
ha="center",
|
|
869
|
+
va="center",
|
|
870
|
+
fontsize=cfg.theme.title_size + 2,
|
|
871
|
+
fontweight="bold",
|
|
872
|
+
color="#991b1b" if (risk >= 0.72 and count > 0) else cfg.theme.text_color,
|
|
873
|
+
zorder=3,
|
|
874
|
+
)
|
|
875
|
+
ax.text(
|
|
876
|
+
c_idx + 0.5,
|
|
877
|
+
y + 0.28,
|
|
878
|
+
f"{pct:.1f}%",
|
|
879
|
+
ha="center",
|
|
880
|
+
va="center",
|
|
881
|
+
fontsize=cfg.theme.caption_size,
|
|
882
|
+
color=cfg.theme.caption_color,
|
|
883
|
+
zorder=3,
|
|
884
|
+
)
|
|
885
|
+
|
|
886
|
+
# Left state band pill
|
|
887
|
+
b_col = state_pal.get(band, "#bdbdbd")
|
|
888
|
+
ax.add_patch(
|
|
889
|
+
FancyBboxPatch(
|
|
890
|
+
(-0.56, y + 0.18),
|
|
891
|
+
0.46,
|
|
892
|
+
0.64,
|
|
893
|
+
boxstyle="round,pad=0.02,rounding_size=0.10",
|
|
894
|
+
facecolor=b_col,
|
|
895
|
+
edgecolor="#ffffff",
|
|
896
|
+
linewidth=1.2,
|
|
897
|
+
zorder=3,
|
|
898
|
+
)
|
|
899
|
+
)
|
|
900
|
+
ax.text(
|
|
901
|
+
-0.33,
|
|
902
|
+
y + 0.50,
|
|
903
|
+
f"Band {band}" if len(band) == 1 else band,
|
|
904
|
+
ha="center",
|
|
905
|
+
va="center",
|
|
906
|
+
fontsize=cfg.theme.caption_size,
|
|
907
|
+
fontweight="bold",
|
|
908
|
+
color=_contrast_text(b_col),
|
|
909
|
+
zorder=4,
|
|
910
|
+
)
|
|
911
|
+
|
|
912
|
+
# Right row total
|
|
913
|
+
r_tot = int(ct.loc[band].sum())
|
|
914
|
+
ax.text(
|
|
915
|
+
n_cols + 0.14,
|
|
916
|
+
y + 0.50,
|
|
917
|
+
f"{r_tot} ({100.0 * r_tot / total_sites:.0f}%)",
|
|
918
|
+
ha="left",
|
|
919
|
+
va="center",
|
|
920
|
+
fontsize=cfg.theme.tick_size,
|
|
921
|
+
fontweight="bold",
|
|
922
|
+
color=cfg.theme.text_color,
|
|
923
|
+
)
|
|
924
|
+
|
|
925
|
+
# Column totals at bottom
|
|
926
|
+
for c_idx, tr in enumerate(trend_cols):
|
|
927
|
+
c_tot = int(ct[tr].sum())
|
|
928
|
+
ax.text(
|
|
929
|
+
c_idx + 0.5,
|
|
930
|
+
-0.28,
|
|
931
|
+
f"Total: {c_tot} ({100.0 * c_tot / total_sites:.0f}%)",
|
|
932
|
+
ha="center",
|
|
933
|
+
va="center",
|
|
934
|
+
fontsize=cfg.theme.caption_size,
|
|
935
|
+
fontweight="bold",
|
|
936
|
+
color=cfg.theme.text_color,
|
|
937
|
+
)
|
|
938
|
+
ax.text(
|
|
939
|
+
c_idx + 0.5,
|
|
940
|
+
n_rows + 0.16,
|
|
941
|
+
tr,
|
|
942
|
+
ha="center",
|
|
943
|
+
va="bottom",
|
|
944
|
+
fontsize=cfg.theme.label_size,
|
|
945
|
+
fontweight="bold",
|
|
946
|
+
color=(
|
|
947
|
+
"#c62828"
|
|
948
|
+
if tr == "Degrading"
|
|
949
|
+
else ("#1565c0" if tr == "Improving" else cfg.theme.text_color)
|
|
950
|
+
),
|
|
951
|
+
)
|
|
952
|
+
|
|
953
|
+
ax.text(
|
|
954
|
+
n_cols + 0.14,
|
|
955
|
+
n_rows + 0.16,
|
|
956
|
+
f"Total\n(n={total_sites})",
|
|
957
|
+
ha="left",
|
|
958
|
+
va="bottom",
|
|
959
|
+
fontsize=cfg.theme.caption_size,
|
|
960
|
+
fontweight="bold",
|
|
961
|
+
color=cfg.theme.caption_color,
|
|
962
|
+
)
|
|
963
|
+
|
|
964
|
+
# Corner callouts
|
|
965
|
+
ax.text(
|
|
966
|
+
0.5,
|
|
967
|
+
-0.58,
|
|
968
|
+
"▲ Priority Action Corner (Poor State + Degrading)",
|
|
969
|
+
ha="left",
|
|
970
|
+
va="center",
|
|
971
|
+
fontsize=cfg.theme.caption_size - 0.5,
|
|
972
|
+
fontweight="bold",
|
|
973
|
+
color="#c62828",
|
|
974
|
+
)
|
|
975
|
+
|
|
976
|
+
ax.set_xlim(-0.65, n_cols + 0.95)
|
|
977
|
+
ax.set_ylim(-0.75, n_rows + 0.48)
|
|
978
|
+
ax.axis("off")
|
|
979
|
+
|
|
980
|
+
fig.suptitle(
|
|
981
|
+
title,
|
|
982
|
+
fontsize=cfg.theme.title_size + 1,
|
|
983
|
+
fontweight=cfg.theme.title_weight,
|
|
984
|
+
color=cfg.theme.text_color,
|
|
985
|
+
y=0.97,
|
|
986
|
+
)
|
|
987
|
+
if subtitle:
|
|
988
|
+
fig.text(
|
|
989
|
+
0.5,
|
|
990
|
+
0.915,
|
|
991
|
+
subtitle,
|
|
992
|
+
ha="center",
|
|
993
|
+
va="top",
|
|
994
|
+
fontsize=cfg.theme.subtitle_size,
|
|
995
|
+
color=cfg.theme.caption_color,
|
|
996
|
+
)
|
|
997
|
+
fig.subplots_adjust(top=0.86 if subtitle else 0.90, bottom=0.05)
|
|
998
|
+
|
|
999
|
+
return fig, ax
|
|
1000
|
+
|
|
1001
|
+
|
|
1002
|
+
def state_trend_heatmap(
|
|
1003
|
+
df: pd.DataFrame,
|
|
1004
|
+
*,
|
|
1005
|
+
group_col: str | None = None,
|
|
1006
|
+
indicator_col: str | None = None,
|
|
1007
|
+
band_col: str | None = None,
|
|
1008
|
+
trend_col: str | None = None,
|
|
1009
|
+
pass_values: tuple[Any, ...] = ("A", "B", "Pass", "PASS", True, "True"),
|
|
1010
|
+
net_trend_threshold: float = 10.0,
|
|
1011
|
+
title: str = "Regional State & Trends Scorecard",
|
|
1012
|
+
subtitle: str | None = None,
|
|
1013
|
+
figsize: tuple[float, float] | None = None,
|
|
1014
|
+
ax: Axes | None = None,
|
|
1015
|
+
config: str | Path | Config | None = None,
|
|
1016
|
+
) -> tuple[Figure, Axes]:
|
|
1017
|
+
"""Render an FMU × Indicator heatmap combining State (% Band A/B or Pass) with Trend glyphs.
|
|
1018
|
+
|
|
1019
|
+
Cell background color encodes current State compliance (0–100%), while an overlaid
|
|
1020
|
+
directional symbol (``▲`` net improving, ``—`` mixed/indeterminate, ``▼`` net degrading)
|
|
1021
|
+
summarizes the trend trajectory for each FMU × Indicator cell.
|
|
1022
|
+
|
|
1023
|
+
Returns:
|
|
1024
|
+
Tuple of ``(fig, ax)``.
|
|
1025
|
+
"""
|
|
1026
|
+
cfg = ensure_config(config)
|
|
1027
|
+
r_group = resolve_column(group_col, cfg, "zone")
|
|
1028
|
+
r_ind = resolve_column(indicator_col, cfg, "indicator")
|
|
1029
|
+
r_band = resolve_column(band_col, cfg, "state_band")
|
|
1030
|
+
r_trend = resolve_column(trend_col, cfg, "trend_direction")
|
|
1031
|
+
validate_columns(df, [r_group, r_ind, r_band, r_trend], context="state_trend_heatmap")
|
|
1032
|
+
|
|
1033
|
+
work = df.copy()
|
|
1034
|
+
if work.empty:
|
|
1035
|
+
raise ValueError("state_trend_heatmap: Input DataFrame is empty.")
|
|
1036
|
+
|
|
1037
|
+
pass_set = {str(v).strip().upper() for v in pass_values}
|
|
1038
|
+
work["_grp"] = work[r_group].astype(str)
|
|
1039
|
+
work["_ind"] = work[r_ind].astype(str)
|
|
1040
|
+
work["_pass"] = work[r_band].astype(str).str.strip().str.upper().isin(pass_set).astype(float)
|
|
1041
|
+
work["_trend"] = _normalize_trend_3level(work, r_trend, cfg)
|
|
1042
|
+
work["_imp"] = (work["_trend"] == "Improving").astype(float)
|
|
1043
|
+
work["_deg"] = (work["_trend"] == "Degrading").astype(float)
|
|
1044
|
+
|
|
1045
|
+
groups = list(dict.fromkeys(work["_grp"].tolist()))
|
|
1046
|
+
indicators = list(dict.fromkeys(work["_ind"].tolist()))
|
|
1047
|
+
|
|
1048
|
+
piv_state = (
|
|
1049
|
+
work.pivot_table(index="_grp", columns="_ind", values="_pass", aggfunc="mean").reindex(
|
|
1050
|
+
index=groups, columns=indicators
|
|
1051
|
+
)
|
|
1052
|
+
* 100.0
|
|
1053
|
+
)
|
|
1054
|
+
piv_net = (
|
|
1055
|
+
work.assign(_net=work["_imp"] - work["_deg"])
|
|
1056
|
+
.pivot_table(index="_grp", columns="_ind", values="_net", aggfunc="mean")
|
|
1057
|
+
.reindex(index=groups, columns=indicators)
|
|
1058
|
+
* 100.0
|
|
1059
|
+
)
|
|
1060
|
+
|
|
1061
|
+
n_rows = len(groups)
|
|
1062
|
+
n_cols = len(indicators)
|
|
1063
|
+
cmap = mcolors.LinearSegmentedColormap.from_list(
|
|
1064
|
+
"stplot_state_ramp", ["#ef5350", "#ffb74d", "#fff176", "#81c784", "#29b6f6"]
|
|
1065
|
+
)
|
|
1066
|
+
|
|
1067
|
+
with mpl_theme(cfg):
|
|
1068
|
+
if ax is None:
|
|
1069
|
+
fig_w = max(8.2, 1.35 * n_cols + 2.6)
|
|
1070
|
+
fig_h = max(4.2, 0.72 * n_rows + 2.0)
|
|
1071
|
+
fig, ax = plt.subplots(figsize=figsize or (fig_w, fig_h))
|
|
1072
|
+
else:
|
|
1073
|
+
fig = ax.figure # type: ignore[assignment]
|
|
1074
|
+
|
|
1075
|
+
ax.set_facecolor(cfg.theme.background_color)
|
|
1076
|
+
|
|
1077
|
+
for r_idx, grp in enumerate(groups):
|
|
1078
|
+
y = n_rows - 1 - r_idx
|
|
1079
|
+
for c_idx, ind in enumerate(indicators):
|
|
1080
|
+
val = piv_state.loc[grp, ind]
|
|
1081
|
+
net = piv_net.loc[grp, ind]
|
|
1082
|
+
if pd.isna(val):
|
|
1083
|
+
fill = "#eef1f5"
|
|
1084
|
+
txt = "—"
|
|
1085
|
+
t_col = "#94a3b8"
|
|
1086
|
+
else:
|
|
1087
|
+
rgba = cmap(float(val) / 100.0)
|
|
1088
|
+
fill = mcolors.to_hex(rgba)
|
|
1089
|
+
t_col = _contrast_text(fill)
|
|
1090
|
+
if pd.isna(net) or abs(float(net)) < net_trend_threshold:
|
|
1091
|
+
glyph = "—"
|
|
1092
|
+
elif float(net) > 0:
|
|
1093
|
+
glyph = "▲"
|
|
1094
|
+
else:
|
|
1095
|
+
glyph = "▼"
|
|
1096
|
+
txt = f"{val:.0f}% {glyph}"
|
|
1097
|
+
|
|
1098
|
+
ax.add_patch(
|
|
1099
|
+
FancyBboxPatch(
|
|
1100
|
+
(c_idx + 0.05, y + 0.08),
|
|
1101
|
+
0.90,
|
|
1102
|
+
0.84,
|
|
1103
|
+
boxstyle="round,pad=0.02,rounding_size=0.08",
|
|
1104
|
+
facecolor=fill,
|
|
1105
|
+
edgecolor="#ffffff",
|
|
1106
|
+
linewidth=1.5,
|
|
1107
|
+
zorder=2,
|
|
1108
|
+
)
|
|
1109
|
+
)
|
|
1110
|
+
ax.text(
|
|
1111
|
+
c_idx + 0.5,
|
|
1112
|
+
y + 0.5,
|
|
1113
|
+
txt,
|
|
1114
|
+
ha="center",
|
|
1115
|
+
va="center",
|
|
1116
|
+
fontsize=cfg.theme.tick_size,
|
|
1117
|
+
fontweight="bold",
|
|
1118
|
+
color=t_col,
|
|
1119
|
+
zorder=3,
|
|
1120
|
+
)
|
|
1121
|
+
|
|
1122
|
+
ax.set_xticks([i + 0.5 for i in range(n_cols)])
|
|
1123
|
+
ax.set_xticklabels(
|
|
1124
|
+
[textwrap.fill(resolve_label(ind, cfg), width=14) for ind in indicators],
|
|
1125
|
+
fontsize=cfg.theme.tick_size,
|
|
1126
|
+
fontweight="bold",
|
|
1127
|
+
)
|
|
1128
|
+
ax.xaxis.tick_top()
|
|
1129
|
+
ax.set_yticks([n_rows - 1 - i + 0.5 for i in range(n_rows)])
|
|
1130
|
+
ax.set_yticklabels(
|
|
1131
|
+
[resolve_label(g, cfg) for g in groups],
|
|
1132
|
+
fontsize=cfg.theme.tick_size,
|
|
1133
|
+
fontweight="bold",
|
|
1134
|
+
)
|
|
1135
|
+
ax.tick_params(length=0, pad=6)
|
|
1136
|
+
ax.set_xlim(0, n_cols)
|
|
1137
|
+
ax.set_ylim(0, n_rows)
|
|
1138
|
+
for spine in ax.spines.values():
|
|
1139
|
+
spine.set_visible(False)
|
|
1140
|
+
|
|
1141
|
+
# Colorbar for State %
|
|
1142
|
+
sm = plt.cm.ScalarMappable(cmap=cmap, norm=mcolors.Normalize(vmin=0, vmax=100))
|
|
1143
|
+
sm.set_array([])
|
|
1144
|
+
cbar = fig.colorbar(sm, ax=ax, fraction=0.032, pad=0.03, aspect=22)
|
|
1145
|
+
cbar.set_label("% Sites Meeting State Target", fontsize=cfg.theme.caption_size)
|
|
1146
|
+
cbar.ax.tick_params(labelsize=cfg.theme.caption_size - 0.5)
|
|
1147
|
+
|
|
1148
|
+
fig.text(
|
|
1149
|
+
0.5,
|
|
1150
|
+
0.03,
|
|
1151
|
+
(
|
|
1152
|
+
"Overlay glyph: ▲ Net improving (> +10%) • "
|
|
1153
|
+
"— Mixed / Indeterminate • ▼ Net degrading (< −10%)"
|
|
1154
|
+
),
|
|
1155
|
+
ha="center",
|
|
1156
|
+
va="bottom",
|
|
1157
|
+
fontsize=cfg.theme.caption_size,
|
|
1158
|
+
color=cfg.theme.caption_color,
|
|
1159
|
+
)
|
|
1160
|
+
|
|
1161
|
+
fig.suptitle(
|
|
1162
|
+
title,
|
|
1163
|
+
fontsize=cfg.theme.title_size + 1,
|
|
1164
|
+
fontweight=cfg.theme.title_weight,
|
|
1165
|
+
color=cfg.theme.text_color,
|
|
1166
|
+
y=0.98,
|
|
1167
|
+
)
|
|
1168
|
+
if subtitle:
|
|
1169
|
+
fig.text(
|
|
1170
|
+
0.5,
|
|
1171
|
+
0.915,
|
|
1172
|
+
subtitle,
|
|
1173
|
+
ha="center",
|
|
1174
|
+
va="top",
|
|
1175
|
+
fontsize=cfg.theme.subtitle_size,
|
|
1176
|
+
color=cfg.theme.caption_color,
|
|
1177
|
+
)
|
|
1178
|
+
fig.subplots_adjust(top=0.80 if subtitle else 0.85, bottom=0.10)
|
|
1179
|
+
|
|
1180
|
+
return fig, ax
|
|
1181
|
+
|
|
1182
|
+
|
|
1183
|
+
def state_trend_sparktable(
|
|
1184
|
+
summary_df: pd.DataFrame,
|
|
1185
|
+
timeseries_df: pd.DataFrame,
|
|
1186
|
+
*,
|
|
1187
|
+
label_col: str | None = None,
|
|
1188
|
+
band_col: str | None = None,
|
|
1189
|
+
value_col: str | None = None,
|
|
1190
|
+
slope_col: str | None = None,
|
|
1191
|
+
trend_col: str | None = None,
|
|
1192
|
+
period_col: str | None = None,
|
|
1193
|
+
unit: str = "",
|
|
1194
|
+
palette: dict[str, str] | None = None,
|
|
1195
|
+
trend_palette: dict[str, str] | None = None,
|
|
1196
|
+
title: str = "Site State & 10-Year Trend Summary",
|
|
1197
|
+
subtitle: str | None = None,
|
|
1198
|
+
figsize: tuple[float, float] | None = None,
|
|
1199
|
+
config: str | Path | Config | None = None,
|
|
1200
|
+
) -> tuple[Figure, Axes]:
|
|
1201
|
+
"""Render an Economist / FT-style visual table pairing State badges with trend sparklines.
|
|
1202
|
+
|
|
1203
|
+
Each row displays:
|
|
1204
|
+
1. Entity label (site or indicator)
|
|
1205
|
+
2. Current NOF Grade badge + current median value
|
|
1206
|
+
3. Mini chronological trend sparkline with highlighted final point
|
|
1207
|
+
4. Annual % change + directional trend pill
|
|
1208
|
+
|
|
1209
|
+
Returns:
|
|
1210
|
+
Tuple of ``(fig, ax)`` where ``ax`` is the primary canvas.
|
|
1211
|
+
"""
|
|
1212
|
+
cfg = ensure_config(config)
|
|
1213
|
+
r_label = resolve_column(label_col, cfg, "site_id")
|
|
1214
|
+
r_band = resolve_column(band_col, cfg, "state_band")
|
|
1215
|
+
r_val = resolve_column(value_col, cfg, "state_value")
|
|
1216
|
+
r_slope = resolve_column(slope_col, cfg, "pct_annual_change")
|
|
1217
|
+
r_trend = resolve_column(trend_col, cfg, "trend_direction")
|
|
1218
|
+
r_period = resolve_column(period_col, cfg, "period")
|
|
1219
|
+
|
|
1220
|
+
validate_columns(
|
|
1221
|
+
summary_df, [r_label, r_band, r_val, r_slope, r_trend], context="state_trend_sparktable"
|
|
1222
|
+
)
|
|
1223
|
+
validate_columns(timeseries_df, [r_label, r_period, r_val], context="state_trend_sparktable")
|
|
1224
|
+
|
|
1225
|
+
work = summary_df.copy().reset_index(drop=True)
|
|
1226
|
+
if work.empty:
|
|
1227
|
+
raise ValueError("state_trend_sparktable: summary_df is empty.")
|
|
1228
|
+
|
|
1229
|
+
work["_trend"] = _normalize_trend_3level(work, r_trend, cfg)
|
|
1230
|
+
s_pal = resolve_palette(palette, cfg, "state_bands")
|
|
1231
|
+
t_pal = resolve_palette(trend_palette, cfg, "trend_directions")
|
|
1232
|
+
trend_sym = {"Improving": "↗", "Indeterminate": "→", "Degrading": "↘", "Not Analysed": "•"}
|
|
1233
|
+
|
|
1234
|
+
n = len(work)
|
|
1235
|
+
|
|
1236
|
+
with mpl_theme(cfg):
|
|
1237
|
+
fig_h = max(3.8, 0.72 * n + 1.9)
|
|
1238
|
+
fig = plt.figure(figsize=figsize or (11.4, fig_h), facecolor="#ffffff")
|
|
1239
|
+
ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
|
|
1240
|
+
ax.set_xlim(0, 10)
|
|
1241
|
+
ax.set_ylim(0, n + 1.8)
|
|
1242
|
+
ax.axis("off")
|
|
1243
|
+
|
|
1244
|
+
# Title & subtitle
|
|
1245
|
+
ax.text(
|
|
1246
|
+
0.35,
|
|
1247
|
+
n + 1.48,
|
|
1248
|
+
title,
|
|
1249
|
+
ha="left",
|
|
1250
|
+
va="center",
|
|
1251
|
+
fontsize=cfg.theme.title_size + 1.5,
|
|
1252
|
+
fontweight="bold",
|
|
1253
|
+
color=cfg.theme.text_color,
|
|
1254
|
+
)
|
|
1255
|
+
if subtitle:
|
|
1256
|
+
ax.text(
|
|
1257
|
+
0.35,
|
|
1258
|
+
n + 1.12,
|
|
1259
|
+
subtitle,
|
|
1260
|
+
ha="left",
|
|
1261
|
+
va="center",
|
|
1262
|
+
fontsize=cfg.theme.subtitle_size,
|
|
1263
|
+
color=cfg.theme.caption_color,
|
|
1264
|
+
)
|
|
1265
|
+
|
|
1266
|
+
# Column headers
|
|
1267
|
+
header_y = n + 0.58
|
|
1268
|
+
ax.add_patch(
|
|
1269
|
+
Rectangle((0.25, header_y - 0.25), 9.5, 0.45, facecolor="#f1f5f9", edgecolor="none")
|
|
1270
|
+
)
|
|
1271
|
+
for hx, htxt, ha in [
|
|
1272
|
+
(0.40, "Site / Indicator", "left"),
|
|
1273
|
+
(3.45, "Current State", "center"),
|
|
1274
|
+
(5.95, "Trend Trajectory", "center"),
|
|
1275
|
+
(8.65, "Annual Change", "center"),
|
|
1276
|
+
]:
|
|
1277
|
+
ax.text(
|
|
1278
|
+
hx,
|
|
1279
|
+
header_y - 0.02,
|
|
1280
|
+
htxt,
|
|
1281
|
+
ha=ha,
|
|
1282
|
+
va="center",
|
|
1283
|
+
fontsize=cfg.theme.caption_size,
|
|
1284
|
+
fontweight="bold",
|
|
1285
|
+
color=cfg.theme.caption_color,
|
|
1286
|
+
)
|
|
1287
|
+
|
|
1288
|
+
for idx, row in work.iterrows():
|
|
1289
|
+
y = n - 0.35 - idx
|
|
1290
|
+
lbl = str(row[r_label])
|
|
1291
|
+
band = str(row[r_band])
|
|
1292
|
+
val = float(row[r_val])
|
|
1293
|
+
slope = float(row[r_slope])
|
|
1294
|
+
tr = str(row["_trend"])
|
|
1295
|
+
|
|
1296
|
+
# Subtle alternating row band
|
|
1297
|
+
if idx % 2 == 1:
|
|
1298
|
+
ax.add_patch(
|
|
1299
|
+
Rectangle(
|
|
1300
|
+
(0.25, y - 0.44), 9.5, 0.88, facecolor="#fafbfd", edgecolor="none", zorder=0
|
|
1301
|
+
)
|
|
1302
|
+
)
|
|
1303
|
+
ax.plot([0.25, 9.75], [y - 0.44, y - 0.44], color="#e2e8f0", linewidth=0.7, zorder=1)
|
|
1304
|
+
|
|
1305
|
+
# Col 1: Label
|
|
1306
|
+
ax.text(
|
|
1307
|
+
0.40,
|
|
1308
|
+
y,
|
|
1309
|
+
resolve_label(lbl, cfg),
|
|
1310
|
+
ha="left",
|
|
1311
|
+
va="center",
|
|
1312
|
+
fontsize=cfg.theme.tick_size,
|
|
1313
|
+
fontweight="bold",
|
|
1314
|
+
color=cfg.theme.text_color,
|
|
1315
|
+
)
|
|
1316
|
+
|
|
1317
|
+
# Col 2: State badge + median value
|
|
1318
|
+
b_col = s_pal.get(band, "#bdbdbd")
|
|
1319
|
+
ax.add_patch(
|
|
1320
|
+
FancyBboxPatch(
|
|
1321
|
+
(2.85, y - 0.26),
|
|
1322
|
+
0.52,
|
|
1323
|
+
0.52,
|
|
1324
|
+
boxstyle="round,pad=0.02,rounding_size=0.08",
|
|
1325
|
+
facecolor=b_col,
|
|
1326
|
+
edgecolor="#ffffff",
|
|
1327
|
+
linewidth=1.0,
|
|
1328
|
+
zorder=2,
|
|
1329
|
+
)
|
|
1330
|
+
)
|
|
1331
|
+
ax.text(
|
|
1332
|
+
3.11,
|
|
1333
|
+
y,
|
|
1334
|
+
band,
|
|
1335
|
+
ha="center",
|
|
1336
|
+
va="center",
|
|
1337
|
+
fontsize=cfg.theme.tick_size,
|
|
1338
|
+
fontweight="bold",
|
|
1339
|
+
color=_contrast_text(b_col),
|
|
1340
|
+
zorder=3,
|
|
1341
|
+
)
|
|
1342
|
+
val_txt = f"{val:g} {unit}".strip()
|
|
1343
|
+
ax.text(
|
|
1344
|
+
3.52,
|
|
1345
|
+
y,
|
|
1346
|
+
val_txt,
|
|
1347
|
+
ha="left",
|
|
1348
|
+
va="center",
|
|
1349
|
+
fontsize=cfg.theme.caption_size,
|
|
1350
|
+
color=cfg.theme.text_color,
|
|
1351
|
+
)
|
|
1352
|
+
|
|
1353
|
+
# Col 3: Sparkline inset
|
|
1354
|
+
sub_ts = timeseries_df[timeseries_df[r_label].astype(str) == lbl].copy()
|
|
1355
|
+
if not sub_ts.empty:
|
|
1356
|
+
ts_vals = (
|
|
1357
|
+
pd.to_numeric(sub_ts[r_val], errors="coerce").dropna().to_numpy(dtype=float)
|
|
1358
|
+
)
|
|
1359
|
+
if len(ts_vals) >= 2:
|
|
1360
|
+
t_min, t_max = float(np.min(ts_vals)), float(np.max(ts_vals))
|
|
1361
|
+
t_span = (t_max - t_min) or 1.0
|
|
1362
|
+
sx = np.linspace(4.85, 7.05, len(ts_vals))
|
|
1363
|
+
sy = (y - 0.26) + 0.52 * ((ts_vals - t_min) / t_span)
|
|
1364
|
+
line_col = t_pal.get(tr, cfg.theme.accent_color)
|
|
1365
|
+
ax.plot(sx, sy, color=line_col, linewidth=2.0, zorder=3)
|
|
1366
|
+
ax.fill_between(sx, y - 0.26, sy, color=line_col, alpha=0.12, zorder=2)
|
|
1367
|
+
ax.scatter(
|
|
1368
|
+
[sx[-1]],
|
|
1369
|
+
[sy[-1]],
|
|
1370
|
+
s=36,
|
|
1371
|
+
color=line_col,
|
|
1372
|
+
edgecolor="#ffffff",
|
|
1373
|
+
lw=0.8,
|
|
1374
|
+
zorder=4,
|
|
1375
|
+
)
|
|
1376
|
+
|
|
1377
|
+
# Col 4: %/yr + trend pill
|
|
1378
|
+
t_col = t_pal.get(tr, "#cbd5e1")
|
|
1379
|
+
ax.text(
|
|
1380
|
+
7.60,
|
|
1381
|
+
y,
|
|
1382
|
+
f"{slope:+.1f}%/yr",
|
|
1383
|
+
ha="left",
|
|
1384
|
+
va="center",
|
|
1385
|
+
fontsize=cfg.theme.caption_size,
|
|
1386
|
+
fontweight="bold",
|
|
1387
|
+
color=cfg.theme.text_color,
|
|
1388
|
+
)
|
|
1389
|
+
ax.add_patch(
|
|
1390
|
+
FancyBboxPatch(
|
|
1391
|
+
(8.48, y - 0.22),
|
|
1392
|
+
1.15,
|
|
1393
|
+
0.44,
|
|
1394
|
+
boxstyle="round,pad=0.02,rounding_size=0.10",
|
|
1395
|
+
facecolor=t_col,
|
|
1396
|
+
edgecolor="none",
|
|
1397
|
+
alpha=0.92,
|
|
1398
|
+
zorder=2,
|
|
1399
|
+
)
|
|
1400
|
+
)
|
|
1401
|
+
ax.text(
|
|
1402
|
+
9.055,
|
|
1403
|
+
y,
|
|
1404
|
+
f"{trend_sym.get(tr, '•')} {tr}",
|
|
1405
|
+
ha="center",
|
|
1406
|
+
va="center",
|
|
1407
|
+
fontsize=cfg.theme.caption_size - 1.2,
|
|
1408
|
+
fontweight="bold",
|
|
1409
|
+
color=_contrast_text(t_col),
|
|
1410
|
+
zorder=3,
|
|
1411
|
+
)
|
|
1412
|
+
|
|
1413
|
+
return fig, ax
|