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/lollipop.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"""Interactive Plotly lollipop templates for state values and diverging trends."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
from stplot.config import (
|
|
11
|
+
Config,
|
|
12
|
+
ensure_config,
|
|
13
|
+
resolve_category_order,
|
|
14
|
+
resolve_column,
|
|
15
|
+
resolve_palette,
|
|
16
|
+
)
|
|
17
|
+
from stplot.theme.plotly import build_plotly_template
|
|
18
|
+
from stplot.transform.columns import validate_columns
|
|
19
|
+
from stplot.transform.filters import derive_trend_direction_3level
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _import_plotly_go() -> Any:
|
|
23
|
+
try:
|
|
24
|
+
import plotly.graph_objects as go
|
|
25
|
+
except ImportError as exc:
|
|
26
|
+
raise ImportError(
|
|
27
|
+
"Interactive Plotly charts require plotly. "
|
|
28
|
+
'Install with: pip install "stplot[interactive]"'
|
|
29
|
+
) from exc
|
|
30
|
+
return go
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def state_lollipop(
|
|
34
|
+
df: pd.DataFrame,
|
|
35
|
+
*,
|
|
36
|
+
site_col: str | None = None,
|
|
37
|
+
value_col: str | None = None,
|
|
38
|
+
band_col: str | None = None,
|
|
39
|
+
sort_ascending: bool = True,
|
|
40
|
+
palette: dict[str, str] | None = None,
|
|
41
|
+
band_order: list[str] | None = None,
|
|
42
|
+
title: str | None = None,
|
|
43
|
+
xlabel: str | None = None,
|
|
44
|
+
ylabel: str = "Site Name",
|
|
45
|
+
legend_title: str = "NOF Grade",
|
|
46
|
+
marker_size: int = 11,
|
|
47
|
+
log_scale: bool = False,
|
|
48
|
+
height: int | None = None,
|
|
49
|
+
config: str | Path | Config | None = None,
|
|
50
|
+
) -> Any:
|
|
51
|
+
"""Create a sorted horizontal Plotly lollipop chart colored by state band.
|
|
52
|
+
|
|
53
|
+
Required columns (resolved via ``config.columns`` unless explicitly overridden):
|
|
54
|
+
- ``site_col`` (default key: ``"site_id"``)
|
|
55
|
+
- ``value_col`` (default key: ``"state_value"``)
|
|
56
|
+
- ``band_col`` (default key: ``"state_band"``)
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
``plotly.graph_objects.Figure`` instance.
|
|
60
|
+
"""
|
|
61
|
+
from stplot.theme.plotly import build_plotly_log_axis
|
|
62
|
+
|
|
63
|
+
go = _import_plotly_go()
|
|
64
|
+
cfg = ensure_config(config)
|
|
65
|
+
|
|
66
|
+
resolved_site = resolve_column(site_col, cfg, "site_id")
|
|
67
|
+
resolved_val = resolve_column(value_col, cfg, "state_value")
|
|
68
|
+
resolved_band = resolve_column(band_col, cfg, "state_band")
|
|
69
|
+
validate_columns(df, [resolved_site, resolved_val, resolved_band], context="state_lollipop")
|
|
70
|
+
|
|
71
|
+
resolved_palette = resolve_palette(palette, cfg, "state_bands")
|
|
72
|
+
resolved_order = resolve_category_order(band_order, cfg, "state_bands")
|
|
73
|
+
|
|
74
|
+
work = df[[resolved_site, resolved_val, resolved_band]].dropna(subset=[resolved_val]).copy()
|
|
75
|
+
if log_scale:
|
|
76
|
+
work = work[pd.to_numeric(work[resolved_val], errors="coerce") > 0].copy()
|
|
77
|
+
# Sort so smallest/best values appear at top when y-axis is reversed (or vice versa)
|
|
78
|
+
work = work.sort_values(by=resolved_val, ascending=not sort_ascending)
|
|
79
|
+
|
|
80
|
+
fig = go.Figure()
|
|
81
|
+
|
|
82
|
+
# Grey lollipop stems from baseline to value
|
|
83
|
+
stem_base = (
|
|
84
|
+
float(pd.to_numeric(work[resolved_val], errors="coerce").min()) * 0.5
|
|
85
|
+
if (log_scale and not work.empty)
|
|
86
|
+
else 0.0
|
|
87
|
+
)
|
|
88
|
+
stem_x: list[float | None] = []
|
|
89
|
+
stem_y: list[str | None] = []
|
|
90
|
+
for _, row in work.iterrows():
|
|
91
|
+
stem_x.extend([stem_base, float(row[resolved_val]), None])
|
|
92
|
+
stem_y.extend([str(row[resolved_site]), str(row[resolved_site]), None])
|
|
93
|
+
|
|
94
|
+
fig.add_trace(
|
|
95
|
+
go.Scatter(
|
|
96
|
+
x=stem_x,
|
|
97
|
+
y=stem_y,
|
|
98
|
+
mode="lines",
|
|
99
|
+
line={"color": "#b0b0b0", "width": 1.2},
|
|
100
|
+
hoverinfo="skip",
|
|
101
|
+
showlegend=False,
|
|
102
|
+
)
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
present_bands = work[resolved_band].astype(str).unique().tolist()
|
|
106
|
+
ordered_bands = [b for b in resolved_order if b in present_bands] + [
|
|
107
|
+
b for b in present_bands if b not in resolved_order
|
|
108
|
+
]
|
|
109
|
+
|
|
110
|
+
for band in ordered_bands:
|
|
111
|
+
sub = work[work[resolved_band].astype(str) == band]
|
|
112
|
+
fig.add_trace(
|
|
113
|
+
go.Scatter(
|
|
114
|
+
x=sub[resolved_val],
|
|
115
|
+
y=sub[resolved_site].astype(str),
|
|
116
|
+
mode="markers",
|
|
117
|
+
name=f"Grade {band}" if len(band) == 1 else band,
|
|
118
|
+
marker={
|
|
119
|
+
"size": marker_size,
|
|
120
|
+
"color": resolved_palette.get(band, "#999999"),
|
|
121
|
+
"line": {"color": "#333333", "width": 0.9},
|
|
122
|
+
},
|
|
123
|
+
hovertemplate=(
|
|
124
|
+
"<b>%{y}</b><br>"
|
|
125
|
+
f"{xlabel or resolved_val}: %{{x:.3g}}<br>"
|
|
126
|
+
f"{legend_title}: {band}<extra></extra>"
|
|
127
|
+
),
|
|
128
|
+
)
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
auto_height = max(420, 24 * len(work) + 140)
|
|
132
|
+
layout_kwargs: dict[str, Any] = {
|
|
133
|
+
"template": build_plotly_template(cfg),
|
|
134
|
+
"title": title,
|
|
135
|
+
"xaxis_title": xlabel or resolved_val,
|
|
136
|
+
"yaxis_title": ylabel,
|
|
137
|
+
"height": height or auto_height,
|
|
138
|
+
"legend": {
|
|
139
|
+
"title": {"text": legend_title},
|
|
140
|
+
"bordercolor": cfg.theme.spine_color,
|
|
141
|
+
"borderwidth": 1,
|
|
142
|
+
},
|
|
143
|
+
"yaxis": {
|
|
144
|
+
"categoryorder": "array",
|
|
145
|
+
"categoryarray": work[resolved_site].astype(str).tolist(),
|
|
146
|
+
},
|
|
147
|
+
}
|
|
148
|
+
if log_scale:
|
|
149
|
+
layout_kwargs["xaxis"] = build_plotly_log_axis(
|
|
150
|
+
work[resolved_val],
|
|
151
|
+
title=xlabel or resolved_val,
|
|
152
|
+
gridcolor=cfg.theme.grid_color,
|
|
153
|
+
gridwidth=cfg.theme.grid_width,
|
|
154
|
+
)
|
|
155
|
+
fig.update_layout(**layout_kwargs)
|
|
156
|
+
if not log_scale:
|
|
157
|
+
fig.add_vline(x=0, line_width=1.2, line_color="#444444")
|
|
158
|
+
return fig
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def trend_lollipop(
|
|
162
|
+
df: pd.DataFrame,
|
|
163
|
+
*,
|
|
164
|
+
site_col: str | None = None,
|
|
165
|
+
value_col: str | None = None,
|
|
166
|
+
direction_col: str | None = None,
|
|
167
|
+
auto_derive_direction: bool = True,
|
|
168
|
+
palette: dict[str, str] | None = None,
|
|
169
|
+
direction_order: list[str] | None = None,
|
|
170
|
+
title: str | None = None,
|
|
171
|
+
subtitle: str | None = None,
|
|
172
|
+
xlabel: str = "Percent annual change (%/year)",
|
|
173
|
+
ylabel: str = "Site Name",
|
|
174
|
+
legend_title: str = "Trend Direction",
|
|
175
|
+
marker_size: int = 11,
|
|
176
|
+
height: int | None = None,
|
|
177
|
+
config: str | Path | Config | None = None,
|
|
178
|
+
) -> Any:
|
|
179
|
+
"""Create a diverging horizontal Plotly lollipop chart for site trends.
|
|
180
|
+
|
|
181
|
+
Centers stems at ``0`` and sorts sites by ``value_col`` (typically
|
|
182
|
+
``Percent.annual.change``) colored by ``Improving`` / ``Indeterminate`` / ``Degrading``.
|
|
183
|
+
|
|
184
|
+
Required columns (resolved via ``config.columns`` unless explicitly overridden):
|
|
185
|
+
- ``site_col`` (default key: ``"site_id"``)
|
|
186
|
+
- ``value_col`` (default key: ``"pct_annual_change"``)
|
|
187
|
+
- ``direction_col`` (optional; if omitted and ``auto_derive_direction=True``,
|
|
188
|
+
derived via :func:`stplot.transform.derive_trend_direction_3level`)
|
|
189
|
+
|
|
190
|
+
Returns:
|
|
191
|
+
``plotly.graph_objects.Figure`` instance.
|
|
192
|
+
"""
|
|
193
|
+
go = _import_plotly_go()
|
|
194
|
+
cfg = ensure_config(config)
|
|
195
|
+
|
|
196
|
+
resolved_site = resolve_column(site_col, cfg, "site_id")
|
|
197
|
+
resolved_val = resolve_column(value_col, cfg, "pct_annual_change")
|
|
198
|
+
validate_columns(df, [resolved_site, resolved_val], context="trend_lollipop")
|
|
199
|
+
|
|
200
|
+
work = df.copy()
|
|
201
|
+
if direction_col is not None:
|
|
202
|
+
validate_columns(work, [direction_col], context="trend_lollipop")
|
|
203
|
+
resolved_dir = direction_col
|
|
204
|
+
elif auto_derive_direction and (
|
|
205
|
+
cfg.columns.get("trend_confidence") in work.columns
|
|
206
|
+
or cfg.columns.get("trend_category") in work.columns
|
|
207
|
+
):
|
|
208
|
+
work = derive_trend_direction_3level(work, out_col="_stplot_trend_dir", config=cfg)
|
|
209
|
+
resolved_dir = "_stplot_trend_dir"
|
|
210
|
+
else:
|
|
211
|
+
resolved_dir = resolve_column(None, cfg, "trend_direction")
|
|
212
|
+
validate_columns(work, [resolved_dir], context="trend_lollipop")
|
|
213
|
+
|
|
214
|
+
resolved_palette = resolve_palette(palette, cfg, "trend_directions")
|
|
215
|
+
resolved_order = resolve_category_order(direction_order, cfg, "trend_directions")
|
|
216
|
+
|
|
217
|
+
work = work[[resolved_site, resolved_val, resolved_dir]].dropna(subset=[resolved_val]).copy()
|
|
218
|
+
# Sort descending so negative (improving for contaminants) appear at top
|
|
219
|
+
work = work.sort_values(by=resolved_val, ascending=False)
|
|
220
|
+
|
|
221
|
+
fig = go.Figure()
|
|
222
|
+
|
|
223
|
+
stem_x: list[float | None] = []
|
|
224
|
+
stem_y: list[str | None] = []
|
|
225
|
+
for _, row in work.iterrows():
|
|
226
|
+
stem_x.extend([0.0, float(row[resolved_val]), None])
|
|
227
|
+
stem_y.extend([str(row[resolved_site]), str(row[resolved_site]), None])
|
|
228
|
+
|
|
229
|
+
fig.add_trace(
|
|
230
|
+
go.Scatter(
|
|
231
|
+
x=stem_x,
|
|
232
|
+
y=stem_y,
|
|
233
|
+
mode="lines",
|
|
234
|
+
line={"color": "#b0b0b0", "width": 1.2},
|
|
235
|
+
hoverinfo="skip",
|
|
236
|
+
showlegend=False,
|
|
237
|
+
)
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
present_dirs = work[resolved_dir].astype(str).unique().tolist()
|
|
241
|
+
ordered_dirs = [d for d in resolved_order if d in present_dirs] + [
|
|
242
|
+
d for d in present_dirs if d not in resolved_order
|
|
243
|
+
]
|
|
244
|
+
|
|
245
|
+
for direction in ordered_dirs:
|
|
246
|
+
sub = work[work[resolved_dir].astype(str) == direction]
|
|
247
|
+
fig.add_trace(
|
|
248
|
+
go.Scatter(
|
|
249
|
+
x=sub[resolved_val],
|
|
250
|
+
y=sub[resolved_site].astype(str),
|
|
251
|
+
mode="markers",
|
|
252
|
+
name=direction,
|
|
253
|
+
marker={
|
|
254
|
+
"size": marker_size,
|
|
255
|
+
"color": resolved_palette.get(direction, "#999999"),
|
|
256
|
+
"line": {"color": "#333333", "width": 0.9},
|
|
257
|
+
},
|
|
258
|
+
hovertemplate=(
|
|
259
|
+
"<b>%{y}</b><br>"
|
|
260
|
+
f"{xlabel}: %{{x:.2f}}<br>"
|
|
261
|
+
f"{legend_title}: {direction}<extra></extra>"
|
|
262
|
+
),
|
|
263
|
+
)
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
full_title = title
|
|
267
|
+
if title and subtitle:
|
|
268
|
+
full_title = f"<b>{title}</b><br><sup>{subtitle}</sup>"
|
|
269
|
+
|
|
270
|
+
auto_height = max(420, 24 * len(work) + 140)
|
|
271
|
+
fig.update_layout(
|
|
272
|
+
template=build_plotly_template(cfg),
|
|
273
|
+
title=full_title,
|
|
274
|
+
xaxis_title=xlabel,
|
|
275
|
+
yaxis_title=ylabel,
|
|
276
|
+
height=height or auto_height,
|
|
277
|
+
legend={
|
|
278
|
+
"title": {"text": legend_title},
|
|
279
|
+
"bordercolor": cfg.theme.spine_color,
|
|
280
|
+
"borderwidth": 1,
|
|
281
|
+
},
|
|
282
|
+
yaxis={"categoryorder": "array", "categoryarray": work[resolved_site].astype(str).tolist()},
|
|
283
|
+
)
|
|
284
|
+
fig.add_vline(x=0, line_width=1.4, line_color="#333333")
|
|
285
|
+
return fig
|