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,474 @@
|
|
|
1
|
+
"""Executive report graphics: KPI cards, grade Sankey, regional heatmap, and FMU fact sheet."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import matplotlib.pyplot as plt
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
from matplotlib.axes import Axes
|
|
12
|
+
from matplotlib.figure import Figure
|
|
13
|
+
from matplotlib.gridspec import GridSpec
|
|
14
|
+
from matplotlib.patches import FancyBboxPatch
|
|
15
|
+
|
|
16
|
+
from stplot.config import (
|
|
17
|
+
Config,
|
|
18
|
+
ensure_config,
|
|
19
|
+
resolve_category_order,
|
|
20
|
+
resolve_column,
|
|
21
|
+
resolve_palette,
|
|
22
|
+
)
|
|
23
|
+
from stplot.plots.maps import publication_map
|
|
24
|
+
from stplot.plots.state import state_band_bar
|
|
25
|
+
from stplot.plots.trends import trend_diverging_bar
|
|
26
|
+
from stplot.theme.mpl import mpl_theme, style_axes
|
|
27
|
+
from stplot.theme.plotly import build_plotly_template
|
|
28
|
+
from stplot.transform.columns import validate_columns
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _hex_to_rgba(hex_color: str, alpha: float = 0.45) -> str:
|
|
32
|
+
cleaned = hex_color.lstrip("#")
|
|
33
|
+
if len(cleaned) != 6:
|
|
34
|
+
return f"rgba(150, 150, 150, {alpha})"
|
|
35
|
+
r, g, b = int(cleaned[0:2], 16), int(cleaned[2:4], 16), int(cleaned[4:6], 16)
|
|
36
|
+
return f"rgba({r}, {g}, {b}, {alpha})"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def kpi_summary_cards(
|
|
40
|
+
metrics: list[dict[str, Any]],
|
|
41
|
+
*,
|
|
42
|
+
title: str | None = None,
|
|
43
|
+
figsize: tuple[float, float] | None = None,
|
|
44
|
+
config: str | Path | Config | None = None,
|
|
45
|
+
) -> tuple[Figure, list[Axes]]:
|
|
46
|
+
"""Render a horizontal strip of executive KPI summary cards for report headers.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
metrics: List of card dictionaries, each containing:
|
|
50
|
+
- ``"value"`` (str): Main headline metric (e.g., ``"53"`` or ``"73%"``).
|
|
51
|
+
- ``"label"`` (str): Metric label (e.g., ``"Sites Monitored"``).
|
|
52
|
+
- ``"subtitle"`` (optional str): Secondary context (e.g., ``"Manawatu FMU"``).
|
|
53
|
+
- ``"color"`` (optional str): Hex color for the top accent bar.
|
|
54
|
+
title: Optional banner heading above the card strip.
|
|
55
|
+
figsize: Optional ``(width, height)`` override.
|
|
56
|
+
config: Optional Config object, preset name, or path to YAML/TOML config.
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
Tuple of ``(fig, axes_list)``.
|
|
60
|
+
"""
|
|
61
|
+
if not metrics:
|
|
62
|
+
raise ValueError("kpi_summary_cards: 'metrics' must contain at least one card dict.")
|
|
63
|
+
|
|
64
|
+
cfg = ensure_config(config)
|
|
65
|
+
n_cards = len(metrics)
|
|
66
|
+
|
|
67
|
+
with mpl_theme(cfg):
|
|
68
|
+
fig_size = figsize or (2.8 * n_cards, 2.25 if title else 1.85)
|
|
69
|
+
fig, axes_raw = plt.subplots(1, n_cards, figsize=fig_size)
|
|
70
|
+
fig.patch.set_facecolor(cfg.theme.background_color)
|
|
71
|
+
axes_list: list[Axes] = list(np.asarray(axes_raw).ravel()) if n_cards > 1 else [axes_raw] # type: ignore[list-item]
|
|
72
|
+
|
|
73
|
+
for ax, card in zip(axes_list, metrics, strict=True):
|
|
74
|
+
ax.set_xlim(0, 1)
|
|
75
|
+
ax.set_ylim(0, 1)
|
|
76
|
+
ax.axis("off")
|
|
77
|
+
|
|
78
|
+
accent = str(card.get("color") or cfg.theme.accent_color)
|
|
79
|
+
box = FancyBboxPatch(
|
|
80
|
+
(0.03, 0.06),
|
|
81
|
+
0.94,
|
|
82
|
+
0.88,
|
|
83
|
+
boxstyle="round,pad=0.02,rounding_size=0.06",
|
|
84
|
+
facecolor="#f8fafc",
|
|
85
|
+
edgecolor=cfg.theme.spine_color,
|
|
86
|
+
linewidth=1.1,
|
|
87
|
+
)
|
|
88
|
+
ax.add_patch(box)
|
|
89
|
+
|
|
90
|
+
# Top accent strip
|
|
91
|
+
top_bar = FancyBboxPatch(
|
|
92
|
+
(0.03, 0.86),
|
|
93
|
+
0.94,
|
|
94
|
+
0.08,
|
|
95
|
+
boxstyle="round,pad=0.02,rounding_size=0.04",
|
|
96
|
+
facecolor=accent,
|
|
97
|
+
edgecolor="none",
|
|
98
|
+
)
|
|
99
|
+
ax.add_patch(top_bar)
|
|
100
|
+
|
|
101
|
+
ax.text(
|
|
102
|
+
0.5,
|
|
103
|
+
0.58,
|
|
104
|
+
str(card["value"]),
|
|
105
|
+
ha="center",
|
|
106
|
+
va="center",
|
|
107
|
+
fontsize=22,
|
|
108
|
+
fontweight="bold",
|
|
109
|
+
color=cfg.theme.text_color,
|
|
110
|
+
)
|
|
111
|
+
ax.text(
|
|
112
|
+
0.5,
|
|
113
|
+
0.30,
|
|
114
|
+
str(card["label"]),
|
|
115
|
+
ha="center",
|
|
116
|
+
va="center",
|
|
117
|
+
fontsize=cfg.theme.label_size - 0.5,
|
|
118
|
+
fontweight="bold",
|
|
119
|
+
color=cfg.theme.text_color,
|
|
120
|
+
)
|
|
121
|
+
if card.get("subtitle"):
|
|
122
|
+
ax.text(
|
|
123
|
+
0.5,
|
|
124
|
+
0.15,
|
|
125
|
+
str(card["subtitle"]),
|
|
126
|
+
ha="center",
|
|
127
|
+
va="center",
|
|
128
|
+
fontsize=cfg.theme.caption_size - 0.5,
|
|
129
|
+
color=cfg.theme.caption_color,
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
if title:
|
|
133
|
+
fig.suptitle(
|
|
134
|
+
title,
|
|
135
|
+
fontsize=cfg.theme.title_size,
|
|
136
|
+
fontweight=cfg.theme.title_weight,
|
|
137
|
+
color=cfg.theme.text_color,
|
|
138
|
+
y=0.98,
|
|
139
|
+
)
|
|
140
|
+
fig.tight_layout(rect=(0.0, 0.0, 1.0, 0.86 if title else 1.0))
|
|
141
|
+
|
|
142
|
+
return fig, axes_list
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def grade_transition_sankey(
|
|
146
|
+
df: pd.DataFrame,
|
|
147
|
+
*,
|
|
148
|
+
from_col: str = "BaselineGrade",
|
|
149
|
+
to_col: str = "CurrentGrade",
|
|
150
|
+
from_label: str = "Baseline",
|
|
151
|
+
to_label: str = "Current",
|
|
152
|
+
band_order: list[str] | None = None,
|
|
153
|
+
palette: dict[str, str] | None = None,
|
|
154
|
+
title: str | None = None,
|
|
155
|
+
height: int = 480,
|
|
156
|
+
width: int = 820,
|
|
157
|
+
config: str | Path | Config | None = None,
|
|
158
|
+
) -> Any:
|
|
159
|
+
"""Create an interactive Plotly Sankey diagram of NPS-FM grade transitions between two periods.
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
df: DataFrame with one row per site and its grade in two periods.
|
|
163
|
+
from_col: Column containing starting/baseline grades (e.g., ``"A"``–``"E"``).
|
|
164
|
+
to_col: Column containing ending/current grades (e.g., ``"A"``–``"E"``).
|
|
165
|
+
from_label: Period label for left-hand nodes (e.g., ``"2015–2019"``).
|
|
166
|
+
to_label: Period label for right-hand nodes (e.g., ``"2021–2025"``).
|
|
167
|
+
band_order: Optional canonical band ordering override.
|
|
168
|
+
palette: Optional state band color palette override.
|
|
169
|
+
title: Optional chart title.
|
|
170
|
+
height: Figure height in pixels.
|
|
171
|
+
width: Figure width in pixels.
|
|
172
|
+
config: Optional Config object, preset name, or path to YAML/TOML config.
|
|
173
|
+
|
|
174
|
+
Returns:
|
|
175
|
+
``plotly.graph_objects.Figure`` instance.
|
|
176
|
+
"""
|
|
177
|
+
try:
|
|
178
|
+
import plotly.graph_objects as go
|
|
179
|
+
except ImportError as exc:
|
|
180
|
+
raise ImportError(
|
|
181
|
+
"Interactive Sankey diagrams require plotly. "
|
|
182
|
+
'Install with: pip install "stplot[interactive]"'
|
|
183
|
+
) from exc
|
|
184
|
+
|
|
185
|
+
cfg = ensure_config(config)
|
|
186
|
+
validate_columns(df, [from_col, to_col], context="grade_transition_sankey")
|
|
187
|
+
|
|
188
|
+
resolved_pal = resolve_palette(palette, cfg, "state_bands")
|
|
189
|
+
resolved_ord = resolve_category_order(band_order, cfg, "state_bands")
|
|
190
|
+
|
|
191
|
+
work = df[[from_col, to_col]].dropna().copy()
|
|
192
|
+
work[from_col] = work[from_col].astype(str)
|
|
193
|
+
work[to_col] = work[to_col].astype(str)
|
|
194
|
+
|
|
195
|
+
present_from = [b for b in resolved_ord if b in set(work[from_col])]
|
|
196
|
+
present_to = [b for b in resolved_ord if b in set(work[to_col])]
|
|
197
|
+
|
|
198
|
+
labels = [f"{from_label}: Band {b}" for b in present_from] + [
|
|
199
|
+
f"{to_label}: Band {b}" for b in present_to
|
|
200
|
+
]
|
|
201
|
+
node_colors = [resolved_pal.get(b, "#bdbdbd") for b in present_from] + [
|
|
202
|
+
resolved_pal.get(b, "#bdbdbd") for b in present_to
|
|
203
|
+
]
|
|
204
|
+
|
|
205
|
+
from_idx = {b: i for i, b in enumerate(present_from)}
|
|
206
|
+
to_idx = {b: len(present_from) + i for i, b in enumerate(present_to)}
|
|
207
|
+
|
|
208
|
+
grouped = work.groupby([from_col, to_col]).size().reset_index(name="count")
|
|
209
|
+
sources = [from_idx[r[from_col]] for _, r in grouped.iterrows() if r[from_col] in from_idx]
|
|
210
|
+
targets = [to_idx[r[to_col]] for _, r in grouped.iterrows() if r[to_col] in to_idx]
|
|
211
|
+
values = [int(r["count"]) for _, r in grouped.iterrows()]
|
|
212
|
+
link_colors = [
|
|
213
|
+
_hex_to_rgba(resolved_pal.get(str(r[from_col]), "#bdbdbd"), alpha=0.45)
|
|
214
|
+
for _, r in grouped.iterrows()
|
|
215
|
+
]
|
|
216
|
+
|
|
217
|
+
fig = go.Figure(
|
|
218
|
+
data=[
|
|
219
|
+
go.Sankey(
|
|
220
|
+
arrangement="snap",
|
|
221
|
+
node={
|
|
222
|
+
"pad": 18,
|
|
223
|
+
"thickness": 22,
|
|
224
|
+
"line": {"color": "#333333", "width": 0.6},
|
|
225
|
+
"label": labels,
|
|
226
|
+
"color": node_colors,
|
|
227
|
+
},
|
|
228
|
+
link={
|
|
229
|
+
"source": sources,
|
|
230
|
+
"target": targets,
|
|
231
|
+
"value": values,
|
|
232
|
+
"color": link_colors,
|
|
233
|
+
},
|
|
234
|
+
)
|
|
235
|
+
]
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
fig.update_layout(
|
|
239
|
+
template=build_plotly_template(cfg),
|
|
240
|
+
title=f"<b>{title}</b>" if title else None,
|
|
241
|
+
height=height,
|
|
242
|
+
width=width,
|
|
243
|
+
margin={"t": 60, "b": 30, "l": 25, "r": 25},
|
|
244
|
+
)
|
|
245
|
+
return fig
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def fmu_indicator_heatmap(
|
|
249
|
+
df: pd.DataFrame,
|
|
250
|
+
*,
|
|
251
|
+
fmu_col: str | None = None,
|
|
252
|
+
indicator_col: str | None = None,
|
|
253
|
+
value_col: str | None = None,
|
|
254
|
+
pass_values: list[Any] | tuple[Any, ...] | None = None,
|
|
255
|
+
vmin: float = 0.0,
|
|
256
|
+
vmax: float = 100.0,
|
|
257
|
+
cmap: str = "YlGnBu",
|
|
258
|
+
fmt: str = ".0f",
|
|
259
|
+
suffix: str = "%",
|
|
260
|
+
title: str | None = None,
|
|
261
|
+
subtitle: str | None = None,
|
|
262
|
+
xlabel: str | None = None,
|
|
263
|
+
ylabel: str | None = None,
|
|
264
|
+
colorbar_label: str = "Sites achieving target (%)",
|
|
265
|
+
figsize: tuple[float, float] | None = None,
|
|
266
|
+
ax: Axes | None = None,
|
|
267
|
+
config: str | Path | Config | None = None,
|
|
268
|
+
) -> tuple[Figure, Axes]:
|
|
269
|
+
"""Plot a regional FMU × Indicator scorecard heatmap with annotated percentage cells.
|
|
270
|
+
|
|
271
|
+
Works with:
|
|
272
|
+
1. **Pre-aggregated percentages** (e.g., numeric ``value_col="PctGood"``),
|
|
273
|
+
2. **Raw One Plan Pass/Fail rows** (boolean ``SitePasses`` or ``"Pass"``/``"Fail"`` strings),
|
|
274
|
+
automatically computing ``% Passing`` per ``(FMU, Indicator)``, or
|
|
275
|
+
3. **Raw NPS-FM NOF Grade rows** by passing ``pass_values=["A", "B"]`` (computes
|
|
276
|
+
``% in Band A or B`` per cell).
|
|
277
|
+
|
|
278
|
+
Returns:
|
|
279
|
+
Tuple of ``(fig, ax)``.
|
|
280
|
+
"""
|
|
281
|
+
cfg = ensure_config(config)
|
|
282
|
+
resolved_fmu = resolve_column(fmu_col, cfg, "fmu")
|
|
283
|
+
if indicator_col is not None:
|
|
284
|
+
resolved_ind = indicator_col
|
|
285
|
+
elif "attribute_label" in cfg.columns and cfg.columns["attribute_label"] in df.columns:
|
|
286
|
+
resolved_ind = cfg.columns["attribute_label"]
|
|
287
|
+
else:
|
|
288
|
+
resolved_ind = resolve_column(None, cfg, "indicator")
|
|
289
|
+
|
|
290
|
+
if value_col is not None:
|
|
291
|
+
resolved_val = value_col
|
|
292
|
+
elif "PctGood" in df.columns:
|
|
293
|
+
resolved_val = "PctGood"
|
|
294
|
+
else:
|
|
295
|
+
resolved_val = resolve_column(None, cfg, "state_band")
|
|
296
|
+
|
|
297
|
+
validate_columns(
|
|
298
|
+
df, [resolved_fmu, resolved_ind, resolved_val], context="fmu_indicator_heatmap"
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
work = df[[resolved_fmu, resolved_ind, resolved_val]].dropna().copy()
|
|
302
|
+
val_series = work[resolved_val]
|
|
303
|
+
|
|
304
|
+
if pass_values is not None:
|
|
305
|
+
allowed = set(pass_values)
|
|
306
|
+
work["_metric"] = val_series.isin(allowed).astype(float) * 100.0
|
|
307
|
+
agg_col = "_metric"
|
|
308
|
+
elif pd.api.types.is_bool_dtype(val_series):
|
|
309
|
+
work["_metric"] = val_series.astype(float) * 100.0
|
|
310
|
+
agg_col = "_metric"
|
|
311
|
+
elif not pd.api.types.is_numeric_dtype(val_series):
|
|
312
|
+
# String Pass/Fail column (e.g., derived One Plan ComplianceResult)
|
|
313
|
+
work["_metric"] = (
|
|
314
|
+
val_series.astype(str).str.strip().str.lower().isin({"pass", "true", "1"}).astype(float)
|
|
315
|
+
* 100.0
|
|
316
|
+
)
|
|
317
|
+
agg_col = "_metric"
|
|
318
|
+
else:
|
|
319
|
+
agg_col = resolved_val
|
|
320
|
+
|
|
321
|
+
pivot = work.pivot_table(
|
|
322
|
+
index=resolved_fmu,
|
|
323
|
+
columns=resolved_ind,
|
|
324
|
+
values=agg_col,
|
|
325
|
+
aggfunc="mean",
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
with mpl_theme(cfg):
|
|
329
|
+
if ax is None:
|
|
330
|
+
fig_w = max(7.5, 1.15 * len(pivot.columns) + 2.8)
|
|
331
|
+
fig_h = max(4.2, 0.65 * len(pivot.index) + 1.8)
|
|
332
|
+
fig, ax = plt.subplots(figsize=figsize or (fig_w, fig_h))
|
|
333
|
+
else:
|
|
334
|
+
fig = ax.figure # type: ignore[assignment]
|
|
335
|
+
|
|
336
|
+
data = pivot.to_numpy(dtype=float)
|
|
337
|
+
im = ax.imshow(data, cmap=cmap, vmin=vmin, vmax=vmax, aspect="auto")
|
|
338
|
+
|
|
339
|
+
# White cell gridlines
|
|
340
|
+
ax.set_xticks(np.arange(len(pivot.columns)))
|
|
341
|
+
ax.set_yticks(np.arange(len(pivot.index)))
|
|
342
|
+
ax.set_xticklabels([str(c) for c in pivot.columns], rotation=30, ha="right")
|
|
343
|
+
ax.set_yticklabels([str(r) for r in pivot.index])
|
|
344
|
+
ax.set_xticks(np.arange(-0.5, len(pivot.columns), 1), minor=True)
|
|
345
|
+
ax.set_yticks(np.arange(-0.5, len(pivot.index), 1), minor=True)
|
|
346
|
+
ax.grid(which="minor", color="#ffffff", linestyle="-", linewidth=2.0)
|
|
347
|
+
ax.grid(which="major", visible=False)
|
|
348
|
+
ax.tick_params(which="minor", length=0)
|
|
349
|
+
|
|
350
|
+
midpoint = (vmin + vmax) / 2.0
|
|
351
|
+
for r_idx in range(data.shape[0]):
|
|
352
|
+
for c_idx in range(data.shape[1]):
|
|
353
|
+
val = data[r_idx, c_idx]
|
|
354
|
+
if np.isnan(val):
|
|
355
|
+
ax.text(
|
|
356
|
+
c_idx,
|
|
357
|
+
r_idx,
|
|
358
|
+
"—",
|
|
359
|
+
ha="center",
|
|
360
|
+
va="center",
|
|
361
|
+
color=cfg.theme.caption_color,
|
|
362
|
+
fontsize=cfg.theme.tick_size,
|
|
363
|
+
)
|
|
364
|
+
else:
|
|
365
|
+
txt_color = "#ffffff" if val >= midpoint else "#1e2a38"
|
|
366
|
+
ax.text(
|
|
367
|
+
c_idx,
|
|
368
|
+
r_idx,
|
|
369
|
+
f"{val:{fmt}}{suffix}",
|
|
370
|
+
ha="center",
|
|
371
|
+
va="center",
|
|
372
|
+
color=txt_color,
|
|
373
|
+
fontsize=cfg.theme.tick_size,
|
|
374
|
+
fontweight="bold",
|
|
375
|
+
)
|
|
376
|
+
|
|
377
|
+
cbar = fig.colorbar(im, ax=ax, fraction=0.035, pad=0.03)
|
|
378
|
+
cbar.set_label(colorbar_label, fontsize=cfg.theme.tick_size, color=cfg.theme.text_color)
|
|
379
|
+
|
|
380
|
+
full_title = title if not subtitle else f"{title}\n{subtitle}" if title else subtitle
|
|
381
|
+
style_axes(ax, title=full_title, xlabel=xlabel, ylabel=ylabel, config=cfg)
|
|
382
|
+
ax.grid(which="major", visible=False)
|
|
383
|
+
for spine in ax.spines.values():
|
|
384
|
+
spine.set_visible(False)
|
|
385
|
+
|
|
386
|
+
return fig, ax
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def fmu_factsheet_panel(
|
|
390
|
+
state_df: pd.DataFrame,
|
|
391
|
+
trend_df: pd.DataFrame,
|
|
392
|
+
fmu_polygons: Any,
|
|
393
|
+
*,
|
|
394
|
+
context_polygons: Any = None,
|
|
395
|
+
rivers: Any = None,
|
|
396
|
+
towns: pd.DataFrame | None = None,
|
|
397
|
+
fmu_name_col: str | None = None,
|
|
398
|
+
highlight_fmu: str | None = None,
|
|
399
|
+
title: str = "FMU Water Quality Fact Sheet",
|
|
400
|
+
subtitle: str | None = None,
|
|
401
|
+
figsize: tuple[float, float] = (14.5, 8.2),
|
|
402
|
+
config: str | Path | Config | None = None,
|
|
403
|
+
) -> tuple[Figure, dict[str, Axes]]:
|
|
404
|
+
"""Build a 1-page multi-panel FMU Fact Sheet combining map, state bar, and trend bar.
|
|
405
|
+
|
|
406
|
+
Layout:
|
|
407
|
+
- Left column: Editorial FMU map (:func:`publication_map`)
|
|
408
|
+
- Top-right: NPS-FM state band breakdown (:func:`state_band_bar`)
|
|
409
|
+
- Bottom-right: Diverging 10-year trend summary (:func:`trend_diverging_bar`)
|
|
410
|
+
|
|
411
|
+
Returns:
|
|
412
|
+
Tuple of ``(fig, {"map": ax_map, "state": ax_state, "trend": ax_trend})``.
|
|
413
|
+
"""
|
|
414
|
+
cfg = ensure_config(config)
|
|
415
|
+
|
|
416
|
+
with mpl_theme(cfg):
|
|
417
|
+
fig = plt.figure(figsize=figsize)
|
|
418
|
+
fig.patch.set_facecolor(cfg.theme.background_color)
|
|
419
|
+
gs = GridSpec(2, 2, figure=fig, width_ratios=[1.05, 1.25], wspace=0.28, hspace=0.44)
|
|
420
|
+
|
|
421
|
+
ax_map = fig.add_subplot(gs[:, 0])
|
|
422
|
+
ax_state = fig.add_subplot(gs[0, 1])
|
|
423
|
+
ax_trend = fig.add_subplot(gs[1, 1])
|
|
424
|
+
|
|
425
|
+
publication_map(
|
|
426
|
+
fmu_polygons,
|
|
427
|
+
context_polygons=context_polygons,
|
|
428
|
+
rivers=rivers,
|
|
429
|
+
towns=towns,
|
|
430
|
+
sites_df=state_df,
|
|
431
|
+
fmu_name_col=fmu_name_col,
|
|
432
|
+
highlight_fmu=highlight_fmu,
|
|
433
|
+
title="Monitoring Site State Grades",
|
|
434
|
+
ax=ax_map,
|
|
435
|
+
config=cfg,
|
|
436
|
+
)
|
|
437
|
+
|
|
438
|
+
state_band_bar(
|
|
439
|
+
state_df,
|
|
440
|
+
group_col=resolve_column(None, cfg, "indicator"),
|
|
441
|
+
title="State Bands by Indicator",
|
|
442
|
+
xlabel=None,
|
|
443
|
+
ax=ax_state,
|
|
444
|
+
config=cfg,
|
|
445
|
+
)
|
|
446
|
+
|
|
447
|
+
trend_diverging_bar(
|
|
448
|
+
trend_df,
|
|
449
|
+
title="10-Year Trend Summary by Indicator",
|
|
450
|
+
ax=ax_trend,
|
|
451
|
+
config=cfg,
|
|
452
|
+
)
|
|
453
|
+
|
|
454
|
+
fig.suptitle(
|
|
455
|
+
title,
|
|
456
|
+
fontsize=cfg.theme.title_size + 3,
|
|
457
|
+
fontweight=cfg.theme.title_weight,
|
|
458
|
+
color=cfg.theme.text_color,
|
|
459
|
+
y=0.98,
|
|
460
|
+
)
|
|
461
|
+
if subtitle:
|
|
462
|
+
fig.text(
|
|
463
|
+
0.5,
|
|
464
|
+
0.935,
|
|
465
|
+
subtitle,
|
|
466
|
+
ha="center",
|
|
467
|
+
va="top",
|
|
468
|
+
fontsize=cfg.theme.subtitle_size,
|
|
469
|
+
color=cfg.theme.caption_color,
|
|
470
|
+
)
|
|
471
|
+
|
|
472
|
+
fig.subplots_adjust(top=0.87, bottom=0.08, left=0.04, right=0.92)
|
|
473
|
+
|
|
474
|
+
return fig, {"map": ax_map, "state": ax_state, "trend": ax_trend}
|
stplot/plots/export.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Unified figure and map export helpers across plotting backends."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from matplotlib.figure import Figure as MplFigure
|
|
9
|
+
|
|
10
|
+
from stplot.config import Config, ensure_config
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def save_figure(
|
|
14
|
+
fig: Any,
|
|
15
|
+
path: str | Path,
|
|
16
|
+
*,
|
|
17
|
+
config: str | Path | Config | None = None,
|
|
18
|
+
dpi: int | None = None,
|
|
19
|
+
bbox_inches: str | None = None,
|
|
20
|
+
transparent: bool | None = None,
|
|
21
|
+
**kwargs: Any,
|
|
22
|
+
) -> Path:
|
|
23
|
+
"""Save a Matplotlib, Plotly, or Folium figure/map with consistent export settings.
|
|
24
|
+
|
|
25
|
+
Automatically creates parent directories if they do not exist.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
fig: Matplotlib ``Figure``, Plotly ``Figure``, or Folium ``Map``.
|
|
29
|
+
path: Output file path (e.g., ``"outputs/state.png"``, ``"outputs/map.html"``).
|
|
30
|
+
config: Optional Config object, preset name, or path to YAML/TOML config.
|
|
31
|
+
dpi: DPI override for raster Matplotlib outputs. Defaults to ``config.export.dpi``.
|
|
32
|
+
bbox_inches: Bounding box override for Matplotlib. Defaults to
|
|
33
|
+
``config.export.bbox_inches``.
|
|
34
|
+
transparent: Transparency override for Matplotlib. Defaults to
|
|
35
|
+
``config.export.transparent``.
|
|
36
|
+
**kwargs: Additional keyword arguments forwarded to the backend's save method.
|
|
37
|
+
|
|
38
|
+
Returns:
|
|
39
|
+
Resolved :class:`pathlib.Path` to the written file.
|
|
40
|
+
|
|
41
|
+
Raises:
|
|
42
|
+
TypeError: If ``fig`` is not a recognized figure or map object.
|
|
43
|
+
"""
|
|
44
|
+
cfg = ensure_config(config)
|
|
45
|
+
out_path = Path(path)
|
|
46
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
47
|
+
|
|
48
|
+
if isinstance(fig, MplFigure):
|
|
49
|
+
fig.savefig(
|
|
50
|
+
out_path,
|
|
51
|
+
dpi=dpi if dpi is not None else cfg.export.dpi,
|
|
52
|
+
bbox_inches=bbox_inches if bbox_inches is not None else cfg.export.bbox_inches,
|
|
53
|
+
transparent=transparent if transparent is not None else cfg.export.transparent,
|
|
54
|
+
**kwargs,
|
|
55
|
+
)
|
|
56
|
+
return out_path
|
|
57
|
+
|
|
58
|
+
# Plotly Figure detection without requiring plotly at import time
|
|
59
|
+
if hasattr(fig, "write_html") and hasattr(fig, "write_image"):
|
|
60
|
+
if out_path.suffix.lower() == ".html":
|
|
61
|
+
fig.write_html(str(out_path), **kwargs)
|
|
62
|
+
else:
|
|
63
|
+
fig.write_image(str(out_path), **kwargs)
|
|
64
|
+
return out_path
|
|
65
|
+
|
|
66
|
+
# Folium Map detection without requiring folium at import time
|
|
67
|
+
if hasattr(fig, "save") and hasattr(fig, "get_root"):
|
|
68
|
+
fig.save(str(out_path), **kwargs)
|
|
69
|
+
return out_path
|
|
70
|
+
|
|
71
|
+
raise TypeError(
|
|
72
|
+
f"Unsupported figure type '{type(fig).__name__}'. "
|
|
73
|
+
"Expected a Matplotlib Figure, Plotly Figure, or Folium Map."
|
|
74
|
+
)
|