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
stplot/plots/state.py
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
"""Templated state band visualization functions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import matplotlib.pyplot as plt
|
|
8
|
+
import matplotlib.ticker as mtick
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
import seaborn as sns
|
|
12
|
+
from matplotlib.axes import Axes
|
|
13
|
+
from matplotlib.figure import Figure
|
|
14
|
+
from matplotlib.patches import Patch
|
|
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.theme.mpl import mpl_theme, style_axes
|
|
24
|
+
from stplot.transform.categories import order_categories
|
|
25
|
+
from stplot.transform.columns import validate_columns
|
|
26
|
+
from stplot.transform.zones import summarise_by_group
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def state_band_bar(
|
|
30
|
+
df: pd.DataFrame,
|
|
31
|
+
*,
|
|
32
|
+
group_col: str | None = None,
|
|
33
|
+
band_col: str | None = None,
|
|
34
|
+
normalize: bool = True,
|
|
35
|
+
horizontal: bool = False,
|
|
36
|
+
palette: dict[str, str] | None = None,
|
|
37
|
+
band_order: list[str] | None = None,
|
|
38
|
+
title: str | None = None,
|
|
39
|
+
xlabel: str | None = None,
|
|
40
|
+
ylabel: str | None = None,
|
|
41
|
+
legend_title: str | None = None,
|
|
42
|
+
figsize: tuple[float, float] | None = None,
|
|
43
|
+
ax: Axes | None = None,
|
|
44
|
+
config: str | Path | Config | None = None,
|
|
45
|
+
) -> tuple[Figure, Axes]:
|
|
46
|
+
"""Plot a stacked bar chart of state band counts or percentages by group.
|
|
47
|
+
|
|
48
|
+
Required columns (resolved via ``config.columns`` unless explicitly overridden):
|
|
49
|
+
- ``group_col`` (default key: ``"zone"``)
|
|
50
|
+
- ``band_col`` (default key: ``"state_band"``)
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
df: Pre-computed state results DataFrame.
|
|
54
|
+
group_col: Column used to group bars (e.g., management zone or indicator).
|
|
55
|
+
band_col: Column containing state band grades (e.g., ``"A"``–``"E"``).
|
|
56
|
+
normalize: If True, plot percentages (0–100%); if False, plot raw site counts.
|
|
57
|
+
horizontal: If True, render horizontal stacked bars instead of vertical bars.
|
|
58
|
+
palette: Optional mapping of band label to color hex override.
|
|
59
|
+
band_order: Optional explicit band display order override.
|
|
60
|
+
title: Optional chart title.
|
|
61
|
+
xlabel: Optional x-axis label override.
|
|
62
|
+
ylabel: Optional y-axis label override.
|
|
63
|
+
legend_title: Optional legend heading. Defaults to resolved ``band_col``.
|
|
64
|
+
figsize: Optional ``(width, height)`` override when ``ax`` is None.
|
|
65
|
+
ax: Optional existing Matplotlib ``Axes`` to draw onto.
|
|
66
|
+
config: Optional Config object, preset name, or path to YAML/TOML config.
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
Tuple of ``(fig, ax)``.
|
|
70
|
+
"""
|
|
71
|
+
cfg = ensure_config(config)
|
|
72
|
+
resolved_group = resolve_column(group_col, cfg, "zone")
|
|
73
|
+
resolved_band = resolve_column(band_col, cfg, "state_band")
|
|
74
|
+
resolved_order = resolve_category_order(band_order, cfg, "state_bands")
|
|
75
|
+
resolved_palette = resolve_palette(palette, cfg, "state_bands")
|
|
76
|
+
|
|
77
|
+
ordered_df = order_categories(
|
|
78
|
+
df,
|
|
79
|
+
col=resolved_band,
|
|
80
|
+
order=resolved_order,
|
|
81
|
+
include_extras=True,
|
|
82
|
+
config=cfg,
|
|
83
|
+
)
|
|
84
|
+
summary = summarise_by_group(
|
|
85
|
+
ordered_df,
|
|
86
|
+
group_col=resolved_group,
|
|
87
|
+
category_col=resolved_band,
|
|
88
|
+
normalize=normalize,
|
|
89
|
+
config=cfg,
|
|
90
|
+
)
|
|
91
|
+
# Keep only categories with at least one non-zero value while preserving canonical order
|
|
92
|
+
active_cols = [c for c in summary.columns if summary[c].sum() > 0]
|
|
93
|
+
summary = summary[active_cols]
|
|
94
|
+
|
|
95
|
+
colors = [resolved_palette.get(str(col), "#999999") for col in summary.columns]
|
|
96
|
+
|
|
97
|
+
with mpl_theme(cfg):
|
|
98
|
+
if ax is None:
|
|
99
|
+
fig, ax = plt.subplots(figsize=figsize or cfg.theme.default_figsize)
|
|
100
|
+
else:
|
|
101
|
+
fig = ax.figure # type: ignore[assignment]
|
|
102
|
+
|
|
103
|
+
kind = "barh" if horizontal else "bar"
|
|
104
|
+
summary.plot(
|
|
105
|
+
kind=kind,
|
|
106
|
+
stacked=True,
|
|
107
|
+
color=colors,
|
|
108
|
+
ax=ax,
|
|
109
|
+
width=0.72,
|
|
110
|
+
edgecolor=cfg.theme.background_color,
|
|
111
|
+
linewidth=0.5,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
metric_label = "Percentage of sites (%)" if normalize else "Number of sites"
|
|
115
|
+
default_x = metric_label if horizontal else resolved_group
|
|
116
|
+
default_y = resolved_group if horizontal else metric_label
|
|
117
|
+
|
|
118
|
+
style_axes(
|
|
119
|
+
ax,
|
|
120
|
+
title=title,
|
|
121
|
+
xlabel=xlabel if xlabel is not None else default_x,
|
|
122
|
+
ylabel=ylabel if ylabel is not None else default_y,
|
|
123
|
+
config=cfg,
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
if not horizontal:
|
|
127
|
+
ax.tick_params(axis="x", rotation=0)
|
|
128
|
+
|
|
129
|
+
ax.legend(
|
|
130
|
+
title=legend_title if legend_title is not None else resolved_band,
|
|
131
|
+
bbox_to_anchor=(1.02, 1.0),
|
|
132
|
+
loc="upper left",
|
|
133
|
+
frameon=False,
|
|
134
|
+
fontsize=cfg.theme.legend_size,
|
|
135
|
+
title_fontsize=cfg.theme.legend_size,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
return fig, ax
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def horizontal_proportion_bar(
|
|
142
|
+
df: pd.DataFrame,
|
|
143
|
+
*,
|
|
144
|
+
group_col: str | None = None,
|
|
145
|
+
category_col: str = "Category",
|
|
146
|
+
category_order: list[str] | None = None,
|
|
147
|
+
palette_key: str = "recreational_swim",
|
|
148
|
+
palette: dict[str, str] | None = None,
|
|
149
|
+
sort_by_first_category: bool = True,
|
|
150
|
+
show_n_in_label: bool = True,
|
|
151
|
+
title: str | None = None,
|
|
152
|
+
xlabel: str | None = None,
|
|
153
|
+
caption: str | None = None,
|
|
154
|
+
show_legend: bool = True,
|
|
155
|
+
figsize: tuple[float, float] | None = None,
|
|
156
|
+
ax: Axes | None = None,
|
|
157
|
+
config: str | Path | Config | None = None,
|
|
158
|
+
) -> tuple[Figure, Axes]:
|
|
159
|
+
"""Plot a sorted horizontal 100% stacked bar chart with ``(n = XX)`` site labels.
|
|
160
|
+
|
|
161
|
+
Ideal for recreational swimming traffic-light breakdowns (Green / Amber / Red) or
|
|
162
|
+
any multi-category proportion summary across sites or zones.
|
|
163
|
+
|
|
164
|
+
Returns:
|
|
165
|
+
Tuple of ``(fig, ax)``.
|
|
166
|
+
"""
|
|
167
|
+
cfg = ensure_config(config)
|
|
168
|
+
resolved_group = resolve_column(group_col, cfg, "site_id")
|
|
169
|
+
validate_columns(df, [resolved_group, category_col], context="horizontal_proportion_bar")
|
|
170
|
+
|
|
171
|
+
resolved_palette = (
|
|
172
|
+
dict(palette)
|
|
173
|
+
if palette is not None
|
|
174
|
+
else cfg.palettes.get(palette_key, resolve_palette(None, cfg, "state_bands"))
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
counts = pd.crosstab(df[resolved_group], df[category_col])
|
|
178
|
+
if category_order is not None:
|
|
179
|
+
order = [c for c in category_order if c in counts.columns]
|
|
180
|
+
else:
|
|
181
|
+
palette_keys = [k for k in resolved_palette if k in counts.columns]
|
|
182
|
+
extras = [c for c in counts.columns if c not in palette_keys]
|
|
183
|
+
order = [*palette_keys, *extras]
|
|
184
|
+
counts = counts[order]
|
|
185
|
+
|
|
186
|
+
totals = counts.sum(axis=1)
|
|
187
|
+
pcts = counts.div(totals.replace(0, pd.NA), axis=0).mul(100.0).fillna(0.0)
|
|
188
|
+
|
|
189
|
+
if sort_by_first_category and len(order) > 0:
|
|
190
|
+
sort_idx = pcts[order[0]].sort_values(ascending=False).index
|
|
191
|
+
pcts = pcts.loc[sort_idx]
|
|
192
|
+
totals = totals.loc[sort_idx]
|
|
193
|
+
|
|
194
|
+
labels = [
|
|
195
|
+
f"{grp} (n = {int(n)})" if show_n_in_label else str(grp)
|
|
196
|
+
for grp, n in zip(pcts.index, totals.to_numpy(), strict=True)
|
|
197
|
+
]
|
|
198
|
+
colors = [resolved_palette.get(str(c), "#999999") for c in pcts.columns]
|
|
199
|
+
|
|
200
|
+
with mpl_theme(cfg):
|
|
201
|
+
if ax is None:
|
|
202
|
+
fig_h = max(4.5, 0.52 * len(pcts) + 1.4)
|
|
203
|
+
fig, ax = plt.subplots(figsize=figsize or (10.0, fig_h))
|
|
204
|
+
else:
|
|
205
|
+
fig = ax.figure # type: ignore[assignment]
|
|
206
|
+
|
|
207
|
+
y_pos = np.arange(len(pcts))
|
|
208
|
+
left = np.zeros(len(pcts), dtype=float)
|
|
209
|
+
for col_name, color in zip(pcts.columns, colors, strict=True):
|
|
210
|
+
vals = pcts[col_name].to_numpy(dtype=float)
|
|
211
|
+
ax.barh(
|
|
212
|
+
y_pos,
|
|
213
|
+
vals,
|
|
214
|
+
left=left,
|
|
215
|
+
height=0.52,
|
|
216
|
+
color=color,
|
|
217
|
+
edgecolor="none",
|
|
218
|
+
label=str(col_name),
|
|
219
|
+
)
|
|
220
|
+
left += vals
|
|
221
|
+
|
|
222
|
+
ax.set_yticks(y_pos)
|
|
223
|
+
ax.set_yticklabels(labels, fontweight="bold")
|
|
224
|
+
ax.set_xlim(0, 100)
|
|
225
|
+
ax.set_xticks(range(0, 101, 10))
|
|
226
|
+
ax.xaxis.set_major_formatter(mtick.PercentFormatter(xmax=100, decimals=0))
|
|
227
|
+
|
|
228
|
+
style_axes(ax, title=title, xlabel=xlabel, ylabel=None, config=cfg)
|
|
229
|
+
ax.yaxis.grid(False)
|
|
230
|
+
ax.spines["left"].set_visible(False)
|
|
231
|
+
ax.tick_params(axis="y", length=0, pad=8)
|
|
232
|
+
|
|
233
|
+
if show_legend:
|
|
234
|
+
ax.legend(
|
|
235
|
+
loc="upper center",
|
|
236
|
+
bbox_to_anchor=(0.5, 1.12),
|
|
237
|
+
ncol=len(pcts.columns),
|
|
238
|
+
frameon=False,
|
|
239
|
+
fontsize=cfg.theme.legend_size,
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
if caption:
|
|
243
|
+
fig.text(
|
|
244
|
+
0.01,
|
|
245
|
+
-0.06,
|
|
246
|
+
caption,
|
|
247
|
+
ha="left",
|
|
248
|
+
va="top",
|
|
249
|
+
fontsize=cfg.theme.caption_size,
|
|
250
|
+
color=cfg.theme.caption_color,
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
return fig, ax
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def state_distribution_plot(
|
|
257
|
+
df: pd.DataFrame,
|
|
258
|
+
*,
|
|
259
|
+
group_col: str | None = None,
|
|
260
|
+
value_col: str | None = None,
|
|
261
|
+
band_col: str | None = None,
|
|
262
|
+
band_thresholds: dict[str, tuple[float, float]] | None = None,
|
|
263
|
+
log_scale: bool = False,
|
|
264
|
+
palette: dict[str, str] | None = None,
|
|
265
|
+
title: str | None = None,
|
|
266
|
+
xlabel: str | None = None,
|
|
267
|
+
ylabel: str | None = None,
|
|
268
|
+
figsize: tuple[float, float] | None = None,
|
|
269
|
+
ax: Axes | None = None,
|
|
270
|
+
config: str | Path | Config | None = None,
|
|
271
|
+
) -> tuple[Figure, Axes]:
|
|
272
|
+
"""Plot site value distributions by FMU/zone overlaid on pastel NOF band shading.
|
|
273
|
+
|
|
274
|
+
Combines clean semi-transparent boxplots with jittered individual site points
|
|
275
|
+
colored by ``NOF_Grade`` (when ``band_col`` is available) over optional horizontal
|
|
276
|
+
NPS-FM band threshold regions.
|
|
277
|
+
|
|
278
|
+
Returns:
|
|
279
|
+
Tuple of ``(fig, ax)``.
|
|
280
|
+
"""
|
|
281
|
+
cfg = ensure_config(config)
|
|
282
|
+
resolved_group = resolve_column(group_col, cfg, "zone")
|
|
283
|
+
resolved_val = resolve_column(value_col, cfg, "state_value")
|
|
284
|
+
validate_columns(df, [resolved_group, resolved_val], context="state_distribution_plot")
|
|
285
|
+
|
|
286
|
+
resolved_band = band_col if band_col is not None else cfg.columns.get("state_band")
|
|
287
|
+
resolved_palette = resolve_palette(palette, cfg, "state_bands")
|
|
288
|
+
work = df.dropna(subset=[resolved_group, resolved_val]).copy()
|
|
289
|
+
|
|
290
|
+
with mpl_theme(cfg):
|
|
291
|
+
if ax is None:
|
|
292
|
+
fig, ax = plt.subplots(figsize=figsize or cfg.theme.default_figsize)
|
|
293
|
+
else:
|
|
294
|
+
fig = ax.figure # type: ignore[assignment]
|
|
295
|
+
|
|
296
|
+
band_handles: list[Patch] = []
|
|
297
|
+
if band_thresholds:
|
|
298
|
+
for band_name, (ymin, ymax) in band_thresholds.items():
|
|
299
|
+
b_col = resolved_palette.get(band_name, "#cccccc")
|
|
300
|
+
ax.axhspan(ymin, ymax, color=b_col, alpha=0.18, zorder=0)
|
|
301
|
+
band_handles.append(Patch(facecolor=b_col, alpha=0.55, label=f"Band {band_name}"))
|
|
302
|
+
|
|
303
|
+
sns.boxplot(
|
|
304
|
+
data=work,
|
|
305
|
+
x=resolved_group,
|
|
306
|
+
y=resolved_val,
|
|
307
|
+
ax=ax,
|
|
308
|
+
width=0.45,
|
|
309
|
+
color="#ffffff",
|
|
310
|
+
showfliers=False,
|
|
311
|
+
boxprops={"edgecolor": cfg.theme.text_color, "linewidth": 1.1, "alpha": 0.75},
|
|
312
|
+
whiskerprops={"color": cfg.theme.text_color, "linewidth": 1.0},
|
|
313
|
+
capprops={"color": cfg.theme.text_color, "linewidth": 1.0},
|
|
314
|
+
medianprops={"color": cfg.theme.text_color, "linewidth": 1.8},
|
|
315
|
+
zorder=2,
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
if resolved_band and resolved_band in work.columns:
|
|
319
|
+
sns.stripplot(
|
|
320
|
+
data=work,
|
|
321
|
+
x=resolved_group,
|
|
322
|
+
y=resolved_val,
|
|
323
|
+
hue=resolved_band,
|
|
324
|
+
palette=resolved_palette,
|
|
325
|
+
ax=ax,
|
|
326
|
+
size=6.5,
|
|
327
|
+
jitter=0.18,
|
|
328
|
+
edgecolor="#222222",
|
|
329
|
+
linewidth=0.6,
|
|
330
|
+
zorder=4,
|
|
331
|
+
)
|
|
332
|
+
if ax.get_legend() is not None:
|
|
333
|
+
ax.get_legend().remove()
|
|
334
|
+
else:
|
|
335
|
+
sns.stripplot(
|
|
336
|
+
data=work,
|
|
337
|
+
x=resolved_group,
|
|
338
|
+
y=resolved_val,
|
|
339
|
+
color=cfg.theme.accent_color,
|
|
340
|
+
ax=ax,
|
|
341
|
+
size=6.5,
|
|
342
|
+
jitter=0.18,
|
|
343
|
+
edgecolor="#222222",
|
|
344
|
+
linewidth=0.6,
|
|
345
|
+
zorder=4,
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
if log_scale:
|
|
349
|
+
from stplot.theme.mpl import format_log_axis
|
|
350
|
+
|
|
351
|
+
format_log_axis(ax, "y")
|
|
352
|
+
|
|
353
|
+
style_axes(
|
|
354
|
+
ax,
|
|
355
|
+
title=title,
|
|
356
|
+
xlabel=xlabel if xlabel is not None else resolved_group,
|
|
357
|
+
ylabel=ylabel if ylabel is not None else resolved_val,
|
|
358
|
+
config=cfg,
|
|
359
|
+
)
|
|
360
|
+
ax.xaxis.grid(False)
|
|
361
|
+
|
|
362
|
+
if band_handles:
|
|
363
|
+
ax.legend(
|
|
364
|
+
handles=band_handles,
|
|
365
|
+
title="NOF Band",
|
|
366
|
+
loc="upper left",
|
|
367
|
+
bbox_to_anchor=(1.02, 1.0),
|
|
368
|
+
frameon=False,
|
|
369
|
+
fontsize=cfg.theme.legend_size,
|
|
370
|
+
title_fontsize=cfg.theme.legend_size,
|
|
371
|
+
)
|
|
372
|
+
|
|
373
|
+
return fig, ax
|