stplot 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. stplot/__init__.py +21 -0
  2. stplot/config/__init__.py +33 -0
  3. stplot/config/loader.py +106 -0
  4. stplot/config/models.py +328 -0
  5. stplot/config/presets/__init__.py +1 -0
  6. stplot/config/presets/default.yaml +208 -0
  7. stplot/config/presets/horizons_one_plan.yaml +59 -0
  8. stplot/io/__init__.py +6 -0
  9. stplot/io/spatial.py +72 -0
  10. stplot/io/tabular.py +154 -0
  11. stplot/plots/__init__.py +122 -0
  12. stplot/plots/barbell.py +400 -0
  13. stplot/plots/batch.py +135 -0
  14. stplot/plots/domains.py +1143 -0
  15. stplot/plots/executive.py +474 -0
  16. stplot/plots/export.py +74 -0
  17. stplot/plots/infographics.py +1118 -0
  18. stplot/plots/lollipop.py +285 -0
  19. stplot/plots/maps.py +738 -0
  20. stplot/plots/matrix.py +190 -0
  21. stplot/plots/one_plan.py +642 -0
  22. stplot/plots/paired.py +437 -0
  23. stplot/plots/scorecards.py +1940 -0
  24. stplot/plots/state.py +373 -0
  25. stplot/plots/state_trends.py +1413 -0
  26. stplot/plots/tables.py +107 -0
  27. stplot/plots/timeseries.py +607 -0
  28. stplot/plots/trends.py +305 -0
  29. stplot/reporting/__init__.py +24 -0
  30. stplot/reporting/captions.py +177 -0
  31. stplot/reporting/html_companion.py +339 -0
  32. stplot/reporting/templates.py +485 -0
  33. stplot/reporting/word.py +369 -0
  34. stplot/theme/__init__.py +25 -0
  35. stplot/theme/folium.py +62 -0
  36. stplot/theme/mpl.py +181 -0
  37. stplot/theme/plotly.py +130 -0
  38. stplot/transform/__init__.py +60 -0
  39. stplot/transform/categories.py +51 -0
  40. stplot/transform/columns.py +103 -0
  41. stplot/transform/filters.py +385 -0
  42. stplot/transform/merge.py +173 -0
  43. stplot/transform/pairing.py +154 -0
  44. stplot/transform/qa.py +297 -0
  45. stplot/transform/tables.py +573 -0
  46. stplot/transform/zones.py +354 -0
  47. stplot-0.1.0.dist-info/METADATA +235 -0
  48. stplot-0.1.0.dist-info/RECORD +49 -0
  49. stplot-0.1.0.dist-info/WHEEL +4 -0
@@ -0,0 +1,607 @@
1
+ """Interactive Plotly time-series templates for pre-computed trends and grade summaries."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+
11
+ from stplot.config import (
12
+ Config,
13
+ ensure_config,
14
+ resolve_category_order,
15
+ resolve_column,
16
+ resolve_palette,
17
+ )
18
+ from stplot.theme.plotly import build_plotly_log_axis, build_plotly_template
19
+ from stplot.transform.columns import validate_columns
20
+ from stplot.transform.zones import summarise_by_group
21
+
22
+
23
+ def _import_plotly_go() -> Any:
24
+ try:
25
+ import plotly.graph_objects as go
26
+ except ImportError as exc:
27
+ raise ImportError(
28
+ "Interactive Plotly charts require plotly. "
29
+ 'Install with: pip install "stplot[interactive]"'
30
+ ) from exc
31
+ return go
32
+
33
+
34
+ def trend_timeseries(
35
+ obs_df: pd.DataFrame,
36
+ *,
37
+ date_col: str = "Date",
38
+ value_col: str = "Value",
39
+ censored_col: str | None = None,
40
+ slope: float | None = None,
41
+ slope_lci: float | None = None,
42
+ slope_uci: float | None = None,
43
+ median: float | None = None,
44
+ trend_start: str | pd.Timestamp | None = None,
45
+ trend_end: str | pd.Timestamp | None = None,
46
+ log_scale: bool = True,
47
+ title: str | None = None,
48
+ xlabel: str = "date",
49
+ ylabel: str | None = None,
50
+ obs_color: str = "#9be2dc",
51
+ censored_color: str = "#f28b82",
52
+ height: int = 420,
53
+ config: str | Path | Config | None = None,
54
+ ) -> Any:
55
+ """Plot monitoring observations overlaid with a pre-computed Sen-slope trend line and CIs.
56
+
57
+ This function does **not** compute statistical trends; it renders pre-computed trend
58
+ parameters (e.g., ``AnnualSenSlope``, ``Sen_Lci``, ``Sen_Uci``, ``Median`` from LWP /
59
+ TimeTrends outputs) alongside raw monitoring observations.
60
+
61
+ Args:
62
+ obs_df: Observations DataFrame containing dates, values, and optional censor flags.
63
+ date_col: Date/timestamp column name in ``obs_df``.
64
+ value_col: Numeric observation value column name in ``obs_df``.
65
+ censored_col: Optional column indicating censored observations (e.g., ``"<"`` / ``"left"``
66
+ for left-censored or ``">"`` / ``"right"`` for right-censored; uncensored rows
67
+ should be ``""``, ``None``, ``"none"``, or ``False``).
68
+ slope: Pre-computed annual Sen slope (units per year).
69
+ slope_lci: Pre-computed lower confidence interval slope (units per year).
70
+ slope_uci: Pre-computed upper confidence interval slope (units per year).
71
+ median: Anchor median value at the midpoint of the trend window. If omitted, uses
72
+ the median of observations within ``[trend_start, trend_end]``.
73
+ trend_start: Start date of the trend window (defaults to first observation date).
74
+ trend_end: End date of the trend window (defaults to last observation date).
75
+ log_scale: If True, use a logarithmic y-axis.
76
+ title: Optional chart title (e.g.,
77
+ ``"Site : with 10 year trend (Extremely likely improving)"``).
78
+ xlabel: X-axis label (default ``"date"``).
79
+ ylabel: Y-axis label (e.g., ``"E. coli [MPN/100mL]"``).
80
+ obs_color: Marker color for uncensored observations.
81
+ censored_color: Marker color for left/right-censored observations.
82
+ height: Figure height in pixels.
83
+ config: Optional Config object, preset name, or path to YAML/TOML config.
84
+
85
+ Returns:
86
+ ``plotly.graph_objects.Figure`` instance.
87
+ """
88
+ go = _import_plotly_go()
89
+ cfg = ensure_config(config)
90
+ validate_columns(obs_df, [date_col, value_col], context="trend_timeseries")
91
+
92
+ work = obs_df.copy()
93
+ work[date_col] = pd.to_datetime(work[date_col])
94
+ work = work.dropna(subset=[date_col, value_col]).sort_values(by=date_col)
95
+
96
+ fig = go.Figure()
97
+
98
+ if censored_col and censored_col in work.columns:
99
+ c_str = work[censored_col].fillna("").astype(str).str.strip().str.lower()
100
+ left_mask = c_str.isin({"<", "left", "l", "lt", "left-censored"})
101
+ right_mask = c_str.isin({">", "right", "r", "gt", "right-censored"})
102
+ uncensored_mask = ~(left_mask | right_mask)
103
+ else:
104
+ left_mask = pd.Series(False, index=work.index)
105
+ right_mask = pd.Series(False, index=work.index)
106
+ uncensored_mask = pd.Series(True, index=work.index)
107
+
108
+ uncensored = work[uncensored_mask]
109
+ if not uncensored.empty:
110
+ fig.add_trace(
111
+ go.Scatter(
112
+ x=uncensored[date_col],
113
+ y=uncensored[value_col],
114
+ mode="markers",
115
+ name="Observed",
116
+ marker={"symbol": "triangle-up", "size": 9, "color": obs_color},
117
+ showlegend=False,
118
+ )
119
+ )
120
+
121
+ left_cens = work[left_mask]
122
+ if not left_cens.empty:
123
+ fig.add_trace(
124
+ go.Scatter(
125
+ x=left_cens[date_col],
126
+ y=left_cens[value_col],
127
+ mode="markers",
128
+ name="Left-censored (<DL)",
129
+ marker={"symbol": "triangle-up", "size": 9, "color": censored_color},
130
+ showlegend=False,
131
+ )
132
+ )
133
+
134
+ right_cens = work[right_mask]
135
+ if not right_cens.empty:
136
+ fig.add_trace(
137
+ go.Scatter(
138
+ x=right_cens[date_col],
139
+ y=right_cens[value_col],
140
+ mode="markers",
141
+ name="Right-censored (>AL)",
142
+ marker={"symbol": "triangle-down", "size": 9, "color": censored_color},
143
+ showlegend=False,
144
+ )
145
+ )
146
+
147
+ # Pre-computed Sen-slope line and CI envelope over [trend_start, trend_end]
148
+ if slope is not None and not work.empty:
149
+ t0 = pd.to_datetime(trend_start) if trend_start is not None else work[date_col].min()
150
+ t1 = pd.to_datetime(trend_end) if trend_end is not None else work[date_col].max()
151
+ t_mid = t0 + (t1 - t0) / 2
152
+
153
+ if median is not None:
154
+ anchor_val = float(median)
155
+ else:
156
+ in_win = work[(work[date_col] >= t0) & (work[date_col] <= t1)][value_col]
157
+ anchor_val = float(in_win.median() if not in_win.empty else work[value_col].median())
158
+
159
+ x_line = pd.date_range(t0, t1, periods=50)
160
+ dt_years = (x_line - t_mid).total_seconds() / (365.25 * 86400.0)
161
+
162
+ def _line_y(s: float) -> np.ndarray:
163
+ vals = anchor_val + s * np.asarray(dt_years, dtype=float)
164
+ return np.where(vals > 0, vals, np.nan) if log_scale else vals
165
+
166
+ fig.add_trace(
167
+ go.Scatter(
168
+ x=x_line,
169
+ y=_line_y(slope),
170
+ mode="lines",
171
+ name="Sen slope",
172
+ line={"color": "#111111", "width": 3.0},
173
+ showlegend=False,
174
+ )
175
+ )
176
+ for ci_slope, ci_name in ((slope_lci, "Lower CI"), (slope_uci, "Upper CI")):
177
+ if ci_slope is not None:
178
+ fig.add_trace(
179
+ go.Scatter(
180
+ x=x_line,
181
+ y=_line_y(ci_slope),
182
+ mode="lines",
183
+ name=ci_name,
184
+ line={"color": "#ffa000", "width": 1.8, "dash": "dash"},
185
+ showlegend=False,
186
+ )
187
+ )
188
+
189
+ fig.update_layout(
190
+ template=build_plotly_template(cfg),
191
+ title=f"<b>{title}</b>" if title else None,
192
+ xaxis_title=xlabel,
193
+ yaxis_title=ylabel or value_col,
194
+ plot_bgcolor=cfg.theme.axes_facecolor,
195
+ paper_bgcolor=cfg.theme.background_color,
196
+ height=height,
197
+ xaxis={"showgrid": False},
198
+ yaxis=(
199
+ build_plotly_log_axis(
200
+ work[value_col],
201
+ gridcolor=cfg.theme.grid_color,
202
+ gridwidth=cfg.theme.grid_width,
203
+ )
204
+ if log_scale
205
+ else {
206
+ "type": "linear",
207
+ "showgrid": True,
208
+ "gridcolor": cfg.theme.grid_color,
209
+ "gridwidth": cfg.theme.grid_width,
210
+ }
211
+ ),
212
+ )
213
+ return fig
214
+
215
+
216
+ def grade_summary_over_time(
217
+ df: pd.DataFrame,
218
+ *,
219
+ period_col: str | None = None,
220
+ band_col: str | None = None,
221
+ period_order: list[str] | None = None,
222
+ band_order: list[str] | None = None,
223
+ palette: dict[str, str] | None = None,
224
+ show_n: bool = True,
225
+ title: str | None = None,
226
+ ylabel: str = "Percentage",
227
+ height: int = 580,
228
+ width: int = 720,
229
+ config: str | Path | Config | None = None,
230
+ ) -> Any:
231
+ """Plot a 100% stacked Plotly bar chart of NOF grades over rolling periods with site counts.
232
+
233
+ Required columns (resolved via ``config.columns`` unless explicitly overridden):
234
+ - ``period_col`` (default key: ``"period"``, e.g., ``"yearz"``)
235
+ - ``band_col`` (default key: ``"state_band"``, e.g., ``"NOF_Grade"``)
236
+
237
+ Returns:
238
+ ``plotly.graph_objects.Figure`` instance.
239
+ """
240
+ go = _import_plotly_go()
241
+ cfg = ensure_config(config)
242
+
243
+ resolved_period = resolve_column(period_col, cfg, "period")
244
+ resolved_band = resolve_column(band_col, cfg, "state_band")
245
+ validate_columns(df, [resolved_period, resolved_band], context="grade_summary_over_time")
246
+
247
+ resolved_palette = resolve_palette(palette, cfg, "state_bands")
248
+ resolved_order = resolve_category_order(band_order, cfg, "state_bands")
249
+
250
+ counts = summarise_by_group(
251
+ df,
252
+ group_col=resolved_period,
253
+ category_col=resolved_band,
254
+ normalize=False,
255
+ config=cfg,
256
+ )
257
+ periods = (
258
+ list(period_order)
259
+ if period_order is not None
260
+ else sorted(counts.index.astype(str).tolist())
261
+ )
262
+ counts.index = counts.index.astype(str)
263
+ counts = counts.reindex(periods).fillna(0)
264
+ totals = counts.sum(axis=1)
265
+ pcts = counts.div(totals.replace(0, pd.NA), axis=0).mul(100.0).fillna(0.0)
266
+
267
+ present_bands = set(counts.columns.astype(str))
268
+ core_bands = {"A", "B", "C", "D", "E"}
269
+ ordered_bands = [b for b in resolved_order if b in present_bands or b in core_bands]
270
+
271
+ fig = go.Figure()
272
+ for band in ordered_bands:
273
+ y_vals = pcts[band].tolist() if band in pcts.columns else [0.0] * len(periods)
274
+ fig.add_trace(
275
+ go.Bar(
276
+ x=periods,
277
+ y=y_vals,
278
+ name=band,
279
+ marker_color=resolved_palette.get(band, "#bdbdbd"),
280
+ hovertemplate=f"<b>%{{x}}</b><br>Grade {band}: %{{y:.1f}}%<extra></extra>",
281
+ )
282
+ )
283
+
284
+ if show_n:
285
+ for period, n_total in zip(periods, totals.tolist(), strict=True):
286
+ fig.add_annotation(
287
+ x=period,
288
+ y=104.5,
289
+ text=str(int(n_total)),
290
+ showarrow=False,
291
+ font={"size": 11, "color": "#555555"},
292
+ )
293
+
294
+ html_title = f"<b>{title.replace(chr(10), '<br>')}</b>" if title else None
295
+ fig.update_layout(
296
+ template=build_plotly_template(cfg),
297
+ barmode="stack",
298
+ title={"text": html_title, "x": 0.01, "xanchor": "left"} if html_title else None,
299
+ yaxis_title=ylabel,
300
+ plot_bgcolor=cfg.theme.axes_facecolor,
301
+ paper_bgcolor=cfg.theme.background_color,
302
+ height=height,
303
+ width=width,
304
+ margin={"t": 95, "b": 85, "l": 65, "r": 70},
305
+ xaxis={"showgrid": False, "tickangle": 30},
306
+ yaxis={
307
+ "range": [0, 110 if show_n else 102],
308
+ "tickvals": [0, 20, 40, 60, 80, 100],
309
+ "showgrid": True,
310
+ "gridcolor": cfg.theme.grid_color,
311
+ "gridwidth": cfg.theme.grid_width,
312
+ },
313
+ legend={"traceorder": "normal"},
314
+ )
315
+ return fig
316
+
317
+
318
+ def state_over_time(
319
+ df: pd.DataFrame,
320
+ *,
321
+ period_col: str | None = None,
322
+ value_col: str | None = None,
323
+ band_col: str | None = None,
324
+ site_col: str | None = None,
325
+ sites: list[str] | None = None,
326
+ thresholds: list[tuple[str, float, float]] | None = None,
327
+ period_order: list[str] | None = None,
328
+ site_markers: dict[str, str] | None = None,
329
+ palette: dict[str, str] | None = None,
330
+ log_y: bool = False,
331
+ title: str | None = None,
332
+ xlabel: str = "",
333
+ ylabel: str | None = None,
334
+ height: int = 470,
335
+ width: int | None = 960,
336
+ config: str | Path | Config | None = None,
337
+ ) -> Any:
338
+ """Plot rolling-period state values over time over pastel NPS-FM NOF Band zones (Plotly).
339
+
340
+ Displays one or more monitoring sites as large charcoal markers (``▲`` for the first site,
341
+ ``▼`` for the second, then ``●`` / ``◆`` / ``■``) with the white NOF Grade letter centered
342
+ inside each marker, laid over horizontal NOF Band background shading (``A``–``E``).
343
+
344
+ Works seamlessly for both single-site history (1 site) and multi-site comparison (2+ sites).
345
+
346
+ Args:
347
+ df: DataFrame with rolling-period state results.
348
+ period_col: Rolling period column (defaults to ``config.columns["period"]``).
349
+ value_col: Numeric state metric column (defaults to ``config.columns["state_value"]``).
350
+ band_col: State band/grade column (defaults to ``config.columns["state_band"]``).
351
+ site_col: Site name column (defaults to ``config.columns["site_id"]``).
352
+ sites: Optional ordered subset of site names to plot.
353
+ thresholds: Optional list of ``(band_label, y_low, y_high)`` tuples defining horizontal
354
+ NOF band background zones.
355
+ period_order: Optional explicit chronological ordering of period labels.
356
+ site_markers: Optional mapping ``{site_name: plotly_marker_symbol}``.
357
+ palette: Optional state band hex color mapping override.
358
+ log_y: If True, use a logarithmic y-axis.
359
+ title: Optional chart title (auto-generated from site name(s) if omitted).
360
+ xlabel: Optional x-axis label.
361
+ ylabel: Optional y-axis label (defaults to ``value_col``).
362
+ height: Figure height in pixels.
363
+ width: Figure width in pixels (or None for responsive width).
364
+ config: Optional Config object, preset name, or path to YAML/TOML config.
365
+
366
+ Returns:
367
+ ``plotly.graph_objects.Figure`` instance.
368
+ """
369
+ go = _import_plotly_go()
370
+ cfg = ensure_config(config)
371
+ r_period = resolve_column(period_col, cfg, "period")
372
+ r_val = resolve_column(value_col, cfg, "state_value")
373
+ r_band = resolve_column(band_col, cfg, "state_band")
374
+ r_site = resolve_column(site_col, cfg, "site_id")
375
+ validate_columns(df, [r_period, r_val, r_band, r_site], context="state_over_time")
376
+
377
+ work = df.copy()
378
+ work["_val"] = pd.to_numeric(work[r_val], errors="coerce")
379
+ work = work.dropna(subset=["_val", r_period]).reset_index(drop=True)
380
+ if work.empty:
381
+ raise ValueError("state_over_time: No valid numeric rows to plot.")
382
+
383
+ work["_site"] = work[r_site].astype(str)
384
+ work["_period"] = work[r_period].astype(str)
385
+ work["_band"] = work[r_band].astype(str)
386
+
387
+ if sites is not None:
388
+ site_list = [str(s) for s in sites]
389
+ work = work[work["_site"].isin(site_list)].copy()
390
+ if work.empty:
391
+ raise ValueError(
392
+ f"state_over_time: None of the requested sites {site_list} were found."
393
+ )
394
+ else:
395
+ site_list = list(dict.fromkeys(work["_site"].tolist()))
396
+
397
+ periods = (
398
+ list(period_order)
399
+ if period_order is not None
400
+ else sorted(work["_period"].unique().tolist())
401
+ )
402
+ resolved_pal = resolve_palette(palette, cfg, "state_bands")
403
+ default_symbols = ["triangle-up", "triangle-down", "circle", "diamond", "square"]
404
+
405
+ fig = go.Figure()
406
+
407
+ # Determine y range
408
+ y_max_data = float(work["_val"].max())
409
+ y_min_data = float(work["_val"].min())
410
+ y_top = y_max_data * 1.08
411
+ if thresholds:
412
+ y_top = max(y_top, max(high for _, _, high in thresholds))
413
+
414
+ # Horizontal pastel NOF band background rectangles
415
+ band_legend_keys: list[str] = []
416
+ if thresholds:
417
+ for b_name, low, high in thresholds:
418
+ b_col = resolved_pal.get(str(b_name), "#d9dee6")
419
+ if str(b_name) not in band_legend_keys:
420
+ band_legend_keys.append(str(b_name))
421
+ fig.add_hrect(
422
+ y0=low,
423
+ y1=high,
424
+ fillcolor=b_col,
425
+ opacity=0.45,
426
+ line_width=0,
427
+ layer="below",
428
+ )
429
+ else:
430
+ band_order = resolve_category_order(None, cfg, "state_bands")
431
+ present = set(work["_band"].unique())
432
+ band_legend_keys = [b for b in band_order if b in present]
433
+
434
+ # Plot each site with its own marker shape & white grade letter inside
435
+ for s_idx, s_name in enumerate(site_list):
436
+ sub = (
437
+ work[work["_site"] == s_name]
438
+ .set_index("_period")
439
+ .reindex(periods)
440
+ .dropna(subset=["_val"])
441
+ .reset_index()
442
+ )
443
+ if sub.empty:
444
+ continue
445
+ symbol = (
446
+ site_markers[s_name]
447
+ if (site_markers and s_name in site_markers)
448
+ else default_symbols[s_idx % len(default_symbols)]
449
+ )
450
+ fig.add_trace(
451
+ go.Scatter(
452
+ x=sub["_period"],
453
+ y=sub["_val"],
454
+ mode="markers+text",
455
+ name=s_name,
456
+ text=sub["_band"],
457
+ textposition="middle center",
458
+ textfont={"color": "#ffffff", "size": 10, "family": "Arial, sans-serif"},
459
+ marker={
460
+ "symbol": symbol,
461
+ "size": 22,
462
+ "color": "rgba(72, 68, 62, 0.78)",
463
+ "line": {"color": "rgba(255, 255, 255, 0.35)", "width": 0.6},
464
+ },
465
+ customdata=np.column_stack([sub["_site"], sub["_band"]]),
466
+ hovertemplate=(
467
+ "<b>%{customdata[0]}</b><br>"
468
+ "Period: %{x}<br>"
469
+ f"{ylabel or r_val}: %{{y:.4g}}<br>"
470
+ "NOF Grade: %{customdata[1]}<extra></extra>"
471
+ ),
472
+ )
473
+ )
474
+
475
+ # Legend-only square swatches for NOF Bands (matching reference style)
476
+ for b_name in band_legend_keys:
477
+ b_col = resolved_pal.get(str(b_name), "#d9dee6")
478
+ fig.add_trace(
479
+ go.Scatter(
480
+ x=[None],
481
+ y=[None],
482
+ mode="markers",
483
+ name=str(b_name),
484
+ marker={"symbol": "square", "size": 9, "color": b_col},
485
+ showlegend=True,
486
+ hoverinfo="skip",
487
+ )
488
+ )
489
+
490
+ if title is None:
491
+ if len(site_list) == 1:
492
+ resolved_title = site_list[0]
493
+ else:
494
+ resolved_title = " -- and -- ".join(site_list[:3])
495
+ else:
496
+ resolved_title = title
497
+
498
+ if log_y:
499
+ from stplot.theme.plotly import build_plotly_log_axis
500
+
501
+ y_axis_cfg = build_plotly_log_axis(
502
+ work["_val"],
503
+ showgrid=True,
504
+ gridcolor="rgba(255, 255, 255, 0.65)",
505
+ gridwidth=1.1,
506
+ max_val=y_top,
507
+ )
508
+ else:
509
+ y_axis_cfg = {
510
+ "showgrid": True,
511
+ "gridcolor": "rgba(255, 255, 255, 0.65)",
512
+ "gridwidth": 1.1,
513
+ "zeroline": False,
514
+ "range": [min(0.0, y_min_data), y_top],
515
+ }
516
+
517
+ fig.update_layout(
518
+ template=build_plotly_template(cfg),
519
+ title={"text": f"<b>{resolved_title}</b>", "x": 0.01, "xanchor": "left"},
520
+ xaxis_title=xlabel or None,
521
+ yaxis_title=ylabel or r_val,
522
+ plot_bgcolor="#eceef1",
523
+ paper_bgcolor=cfg.theme.background_color,
524
+ height=height,
525
+ width=width,
526
+ margin={"t": 72, "b": 105, "l": 72, "r": 185},
527
+ xaxis={
528
+ "type": "category",
529
+ "categoryorder": "array",
530
+ "categoryarray": periods,
531
+ "tickangle": 90,
532
+ "showgrid": False,
533
+ },
534
+ yaxis=y_axis_cfg,
535
+ legend={
536
+ "x": 1.02,
537
+ "y": 0.98,
538
+ "xanchor": "left",
539
+ "yanchor": "top",
540
+ "bgcolor": "rgba(255,255,255,0)",
541
+ "traceorder": "normal",
542
+ },
543
+ )
544
+ return fig
545
+
546
+
547
+ def state_over_time_comparison(
548
+ df: pd.DataFrame,
549
+ *,
550
+ sites: list[str] | None = None,
551
+ period_col: str | None = None,
552
+ value_col: str | None = None,
553
+ band_col: str | None = None,
554
+ site_col: str | None = None,
555
+ thresholds: list[tuple[str, float, float]] | None = None,
556
+ period_order: list[str] | None = None,
557
+ site_markers: dict[str, str] | None = None,
558
+ palette: dict[str, str] | None = None,
559
+ log_y: bool = False,
560
+ title: str | None = None,
561
+ xlabel: str = "",
562
+ ylabel: str | None = None,
563
+ height: int = 470,
564
+ width: int | None = 980,
565
+ config: str | Path | Config | None = None,
566
+ ) -> Any:
567
+ """Compare rolling-period state values over time for two or more sites on one chart (Plotly).
568
+
569
+ Convenience wrapper around :func:`state_over_time` tailored for multi-site comparison
570
+ (e.g., upstream vs downstream or two focal catchment sites) using contrasting triangle
571
+ orientations (``▲`` vs ``▼``) with NOF Grade letters inside each marker.
572
+
573
+ Returns:
574
+ ``plotly.graph_objects.Figure`` instance.
575
+ """
576
+ cfg = ensure_config(config)
577
+ r_site = resolve_column(site_col, cfg, "site_id")
578
+ validate_columns(df, [r_site], context="state_over_time_comparison")
579
+ unique_sites = (
580
+ [str(s) for s in sites]
581
+ if sites is not None
582
+ else list(dict.fromkeys(df[r_site].dropna().astype(str).tolist()))
583
+ )
584
+ if len(unique_sites) < 2:
585
+ raise ValueError(
586
+ "state_over_time_comparison requires at least 2 distinct sites. "
587
+ "Use state_over_time() for a single site."
588
+ )
589
+ return state_over_time(
590
+ df,
591
+ period_col=period_col,
592
+ value_col=value_col,
593
+ band_col=band_col,
594
+ site_col=site_col,
595
+ sites=sites,
596
+ thresholds=thresholds,
597
+ period_order=period_order,
598
+ site_markers=site_markers,
599
+ palette=palette,
600
+ log_y=log_y,
601
+ title=title,
602
+ xlabel=xlabel,
603
+ ylabel=ylabel,
604
+ height=height,
605
+ width=width,
606
+ config=cfg,
607
+ )