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/maps.py
ADDED
|
@@ -0,0 +1,738 @@
|
|
|
1
|
+
"""Interactive Folium map templates for FMU state and trends visualization."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from html import escape
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
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.io.spatial import read_spatial
|
|
19
|
+
from stplot.theme.folium import build_legend_html
|
|
20
|
+
from stplot.transform.columns import validate_columns
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _to_wgs84(
|
|
24
|
+
x: pd.Series,
|
|
25
|
+
y: pd.Series,
|
|
26
|
+
crs: str | int,
|
|
27
|
+
) -> tuple[pd.Series, pd.Series]:
|
|
28
|
+
"""Convert x/y coordinates from ``crs`` to WGS84 (lon, lat)."""
|
|
29
|
+
crs_str = str(crs).upper()
|
|
30
|
+
if crs_str in {"EPSG:4326", "4326", "WGS84"}:
|
|
31
|
+
return x.astype(float), y.astype(float)
|
|
32
|
+
|
|
33
|
+
try:
|
|
34
|
+
from pyproj import Transformer
|
|
35
|
+
except ImportError as exc:
|
|
36
|
+
raise ImportError(
|
|
37
|
+
"Reprojecting coordinates (e.g. NZTM EPSG:2193 -> WGS84) requires pyproj. "
|
|
38
|
+
'Install with: pip install "stplot[geo]"'
|
|
39
|
+
) from exc
|
|
40
|
+
|
|
41
|
+
transformer = Transformer.from_crs(crs, "EPSG:4326", always_xy=True)
|
|
42
|
+
lon, lat = transformer.transform(x.to_numpy(dtype=float), y.to_numpy(dtype=float))
|
|
43
|
+
return pd.Series(lon, index=x.index), pd.Series(lat, index=y.index)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def fmu_state_map(
|
|
47
|
+
df: pd.DataFrame,
|
|
48
|
+
*,
|
|
49
|
+
site_col: str | None = None,
|
|
50
|
+
band_col: str | None = None,
|
|
51
|
+
x_col: str | None = None,
|
|
52
|
+
y_col: str | None = None,
|
|
53
|
+
crs: str | int | None = None,
|
|
54
|
+
boundary: Any = None,
|
|
55
|
+
boundary_filter_col: str | None = None,
|
|
56
|
+
boundary_filter_value: str | None = None,
|
|
57
|
+
palette: dict[str, str] | None = None,
|
|
58
|
+
band_order: list[str] | None = None,
|
|
59
|
+
title: str | None = None,
|
|
60
|
+
legend_title: str = "Legend",
|
|
61
|
+
tiles: str = (
|
|
62
|
+
"https://server.arcgisonline.com/ArcGIS/rest/services/"
|
|
63
|
+
"Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}"
|
|
64
|
+
),
|
|
65
|
+
attr: str | None = "Tiles © Esri — Esri, DeLorme, NAVTEQ",
|
|
66
|
+
marker_radius: float = 7.0,
|
|
67
|
+
zoom_start: int = 9,
|
|
68
|
+
config: str | Path | Config | None = None,
|
|
69
|
+
) -> Any:
|
|
70
|
+
"""Create an interactive Folium map of monitoring sites colored by state band.
|
|
71
|
+
|
|
72
|
+
Matches the Horizons FMU map style: light grey Esri basemap, black boundary outline,
|
|
73
|
+
colored circular markers with dark borders, floating top-left title badge,
|
|
74
|
+
bottom-right legend, and scale bar.
|
|
75
|
+
|
|
76
|
+
Required columns (resolved via ``config.columns`` unless explicitly overridden):
|
|
77
|
+
- ``site_col`` (default key: ``"site_id"``)
|
|
78
|
+
- ``band_col`` (default key: ``"state_band"``)
|
|
79
|
+
- ``x_col`` (default key: ``"x"``, e.g., ``"NZTM.X"``)
|
|
80
|
+
- ``y_col`` (default key: ``"y"``, e.g., ``"NZTM.Y"``)
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
df: Pre-computed state results DataFrame.
|
|
84
|
+
site_col: Site name/ID column override.
|
|
85
|
+
band_col: State band column override.
|
|
86
|
+
x_col: Easting/longitude column override.
|
|
87
|
+
y_col: Northing/latitude column override.
|
|
88
|
+
crs: CRS of ``x_col``/``y_col`` (defaults to ``config.columns["crs"]`` or ``"EPSG:2193"``).
|
|
89
|
+
boundary: Optional boundary layer — a ``GeoDataFrame``, local file path, REST GeoJSON
|
|
90
|
+
URL, or named key in ``config.spatial_sources`` (e.g., ``"horizons_fmu"``).
|
|
91
|
+
boundary_filter_col: Optional attribute column on ``boundary`` to filter by.
|
|
92
|
+
boundary_filter_value: Optional attribute value to filter ``boundary`` to a single FMU.
|
|
93
|
+
palette: Optional state band color mapping override.
|
|
94
|
+
band_order: Optional state band legend order override.
|
|
95
|
+
title: Optional title shown in a floating top-left badge (e.g., ``"E. coli"``).
|
|
96
|
+
legend_title: Heading for the bottom-right legend box.
|
|
97
|
+
tiles: Folium tile layer name or XYZ URL (defaults to Esri World Light Gray Base).
|
|
98
|
+
attr: Tile attribution string required when ``tiles`` is a custom URL.
|
|
99
|
+
marker_radius: CircleMarker radius in pixels.
|
|
100
|
+
zoom_start: Initial zoom level when no boundary bounds are fitted.
|
|
101
|
+
config: Optional Config object, preset name, or path to YAML/TOML config.
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
``folium.Map`` instance.
|
|
105
|
+
"""
|
|
106
|
+
try:
|
|
107
|
+
import folium
|
|
108
|
+
except ImportError as exc:
|
|
109
|
+
raise ImportError(
|
|
110
|
+
'Interactive maps require folium. Install with: pip install "stplot[geo]"'
|
|
111
|
+
) from exc
|
|
112
|
+
|
|
113
|
+
cfg = ensure_config(config)
|
|
114
|
+
resolved_site = resolve_column(site_col, cfg, "site_id")
|
|
115
|
+
resolved_band = resolve_column(band_col, cfg, "state_band")
|
|
116
|
+
resolved_x = resolve_column(x_col, cfg, "x")
|
|
117
|
+
resolved_y = resolve_column(y_col, cfg, "y")
|
|
118
|
+
resolved_crs = crs if crs is not None else cfg.columns.get("crs", "EPSG:2193")
|
|
119
|
+
|
|
120
|
+
validate_columns(
|
|
121
|
+
df,
|
|
122
|
+
[resolved_site, resolved_band, resolved_x, resolved_y],
|
|
123
|
+
context="fmu_state_map",
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
resolved_palette = resolve_palette(palette, cfg, "state_bands")
|
|
127
|
+
resolved_order = resolve_category_order(band_order, cfg, "state_bands")
|
|
128
|
+
|
|
129
|
+
work = df.dropna(subset=[resolved_x, resolved_y]).copy()
|
|
130
|
+
if work.empty:
|
|
131
|
+
raise ValueError("fmu_state_map: No rows with valid coordinates remain after dropping NAs.")
|
|
132
|
+
|
|
133
|
+
lon, lat = _to_wgs84(work[resolved_x], work[resolved_y], resolved_crs)
|
|
134
|
+
work["_lon"] = lon
|
|
135
|
+
work["_lat"] = lat
|
|
136
|
+
|
|
137
|
+
center = [float(work["_lat"].mean()), float(work["_lon"].mean())]
|
|
138
|
+
map_kwargs: dict[str, Any] = {
|
|
139
|
+
"location": center,
|
|
140
|
+
"zoom_start": zoom_start,
|
|
141
|
+
"tiles": tiles,
|
|
142
|
+
"control_scale": True,
|
|
143
|
+
}
|
|
144
|
+
if tiles.startswith(("http://", "https://")) and attr:
|
|
145
|
+
map_kwargs["attr"] = attr
|
|
146
|
+
fmap = folium.Map(**map_kwargs)
|
|
147
|
+
|
|
148
|
+
# Optional boundary polygon overlay
|
|
149
|
+
if boundary is not None:
|
|
150
|
+
gdf = (
|
|
151
|
+
read_spatial(boundary, crs="EPSG:4326", config=cfg)
|
|
152
|
+
if isinstance(boundary, (str, Path))
|
|
153
|
+
else boundary.to_crs("EPSG:4326")
|
|
154
|
+
if getattr(boundary, "crs", None) is not None
|
|
155
|
+
else boundary
|
|
156
|
+
)
|
|
157
|
+
if boundary_filter_col and boundary_filter_value is not None:
|
|
158
|
+
gdf = gdf[gdf[boundary_filter_col] == boundary_filter_value]
|
|
159
|
+
if len(gdf) > 0:
|
|
160
|
+
folium.GeoJson(
|
|
161
|
+
gdf,
|
|
162
|
+
name="Boundary",
|
|
163
|
+
style_function=lambda _feat: {
|
|
164
|
+
"fillColor": "#ffffff",
|
|
165
|
+
"fillOpacity": 0.15,
|
|
166
|
+
"color": "#111111",
|
|
167
|
+
"weight": 2.0,
|
|
168
|
+
},
|
|
169
|
+
).add_to(fmap)
|
|
170
|
+
minx, miny, maxx, maxy = gdf.total_bounds
|
|
171
|
+
fmap.fit_bounds([[float(miny), float(minx)], [float(maxy), float(maxx)]])
|
|
172
|
+
|
|
173
|
+
# Site CircleMarkers
|
|
174
|
+
for _, row in work.iterrows():
|
|
175
|
+
band = str(row[resolved_band])
|
|
176
|
+
color = resolved_palette.get(band, "#999999")
|
|
177
|
+
site_name = str(row[resolved_site])
|
|
178
|
+
popup_html = f"<b>{escape(site_name)}</b><br>{escape(resolved_band)}: {escape(band)}"
|
|
179
|
+
folium.CircleMarker(
|
|
180
|
+
location=[float(row["_lat"]), float(row["_lon"])],
|
|
181
|
+
radius=marker_radius,
|
|
182
|
+
color="#222222",
|
|
183
|
+
weight=1.0,
|
|
184
|
+
fill=True,
|
|
185
|
+
fill_color=color,
|
|
186
|
+
fill_opacity=0.92,
|
|
187
|
+
tooltip=f"{site_name} ({band})",
|
|
188
|
+
popup=folium.Popup(popup_html, max_width=260),
|
|
189
|
+
).add_to(fmap)
|
|
190
|
+
|
|
191
|
+
# Floating top-left title badge
|
|
192
|
+
if title:
|
|
193
|
+
title_html = (
|
|
194
|
+
'<div style="position:fixed;top:12px;left:54px;z-index:9999;'
|
|
195
|
+
f"background:{escape(cfg.theme.background_color)};color:{escape(cfg.theme.text_color)};"
|
|
196
|
+
f"font-family:{escape(cfg.theme.font_family)},sans-serif;font-size:15px;"
|
|
197
|
+
"font-weight:700;padding:6px 14px;border-radius:4px;"
|
|
198
|
+
'box-shadow:0 1px 5px rgba(0,0,0,0.25);">'
|
|
199
|
+
f"{escape(title)}</div>"
|
|
200
|
+
)
|
|
201
|
+
fmap.get_root().html.add_child(folium.Element(title_html))
|
|
202
|
+
|
|
203
|
+
# Bottom-right legend matching active bands (or canonical order)
|
|
204
|
+
present_bands = set(work[resolved_band].astype(str).unique())
|
|
205
|
+
core_bands = {"A", "B", "C", "D", "E"}
|
|
206
|
+
display_order = [b for b in resolved_order if b in present_bands or b in core_bands]
|
|
207
|
+
legend_palette = {
|
|
208
|
+
(f"Grade {b}" if len(b) == 1 else b): resolved_palette.get(b, "#999999")
|
|
209
|
+
for b in display_order
|
|
210
|
+
if b in resolved_palette
|
|
211
|
+
}
|
|
212
|
+
legend_html = build_legend_html(legend_title, legend_palette, config=cfg).replace(
|
|
213
|
+
"left:30px;", "right:20px;"
|
|
214
|
+
)
|
|
215
|
+
fmap.get_root().html.add_child(folium.Element(legend_html))
|
|
216
|
+
|
|
217
|
+
return fmap
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def static_fmu_map(
|
|
221
|
+
df: pd.DataFrame,
|
|
222
|
+
*,
|
|
223
|
+
boundary: Any = None,
|
|
224
|
+
boundary_filter_col: str | None = None,
|
|
225
|
+
boundary_filter_value: str | None = None,
|
|
226
|
+
mode: str = "state",
|
|
227
|
+
site_col: str | None = None,
|
|
228
|
+
category_col: str | None = None,
|
|
229
|
+
x_col: str | None = None,
|
|
230
|
+
y_col: str | None = None,
|
|
231
|
+
crs: str | int | None = None,
|
|
232
|
+
palette: dict[str, str] | None = None,
|
|
233
|
+
category_order: list[str] | None = None,
|
|
234
|
+
title: str | None = None,
|
|
235
|
+
subtitle: str | None = None,
|
|
236
|
+
legend_title: str | None = None,
|
|
237
|
+
show_north_arrow: bool = True,
|
|
238
|
+
show_scale_bar: bool = True,
|
|
239
|
+
marker_size: float = 110.0,
|
|
240
|
+
figsize: tuple[float, float] | None = None,
|
|
241
|
+
ax: Any = None,
|
|
242
|
+
config: str | Path | Config | None = None,
|
|
243
|
+
) -> tuple[Any, Any]:
|
|
244
|
+
"""Create a 300-DPI static publication map using GeoPandas and Matplotlib.
|
|
245
|
+
|
|
246
|
+
Supports both ``mode="state"`` (grade-colored circles ``A``–``E``) and
|
|
247
|
+
``mode="trend"`` (upward ``▲`` Improving, circle ``●`` Indeterminate, downward ``▼``
|
|
248
|
+
Degrading) with optional boundary polygon overlay, north arrow, and km scale bar.
|
|
249
|
+
|
|
250
|
+
Returns:
|
|
251
|
+
Tuple of ``(fig, ax)``.
|
|
252
|
+
"""
|
|
253
|
+
try:
|
|
254
|
+
import geopandas as gpd
|
|
255
|
+
except ImportError as exc:
|
|
256
|
+
raise ImportError(
|
|
257
|
+
'Static maps require geopandas. Install with: pip install "stplot[geo]"'
|
|
258
|
+
) from exc
|
|
259
|
+
|
|
260
|
+
import matplotlib.pyplot as plt
|
|
261
|
+
from matplotlib.lines import Line2D
|
|
262
|
+
|
|
263
|
+
from stplot.theme.mpl import mpl_theme
|
|
264
|
+
from stplot.transform.filters import derive_trend_direction_3level
|
|
265
|
+
|
|
266
|
+
cfg = ensure_config(config)
|
|
267
|
+
resolved_x = resolve_column(x_col, cfg, "x")
|
|
268
|
+
resolved_y = resolve_column(y_col, cfg, "y")
|
|
269
|
+
resolved_crs = crs if crs is not None else cfg.columns.get("crs", "EPSG:2193")
|
|
270
|
+
|
|
271
|
+
work = df.copy()
|
|
272
|
+
if mode == "trend":
|
|
273
|
+
if category_col is not None:
|
|
274
|
+
resolved_cat = category_col
|
|
275
|
+
elif (
|
|
276
|
+
cfg.columns.get("trend_confidence") in work.columns
|
|
277
|
+
or cfg.columns.get("trend_category") in work.columns
|
|
278
|
+
):
|
|
279
|
+
work = derive_trend_direction_3level(work, out_col="_stplot_trend_dir", config=cfg)
|
|
280
|
+
resolved_cat = "_stplot_trend_dir"
|
|
281
|
+
else:
|
|
282
|
+
resolved_cat = resolve_column(None, cfg, "trend_direction")
|
|
283
|
+
palette_key = "trend_directions"
|
|
284
|
+
order_key = "trend_directions"
|
|
285
|
+
default_legend = "Trend Direction"
|
|
286
|
+
else:
|
|
287
|
+
resolved_cat = resolve_column(category_col, cfg, "state_band")
|
|
288
|
+
palette_key = "state_bands"
|
|
289
|
+
order_key = "state_bands"
|
|
290
|
+
default_legend = "NOF Grade"
|
|
291
|
+
|
|
292
|
+
validate_columns(work, [resolved_x, resolved_y, resolved_cat], context="static_fmu_map")
|
|
293
|
+
|
|
294
|
+
work = work.dropna(subset=[resolved_x, resolved_y, resolved_cat]).copy()
|
|
295
|
+
if work.empty:
|
|
296
|
+
raise ValueError("static_fmu_map: No rows with valid coordinates remain.")
|
|
297
|
+
|
|
298
|
+
pts_gdf = gpd.GeoDataFrame(
|
|
299
|
+
work,
|
|
300
|
+
geometry=gpd.points_from_xy(work[resolved_x], work[resolved_y]),
|
|
301
|
+
crs=resolved_crs,
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
resolved_palette = resolve_palette(palette, cfg, palette_key)
|
|
305
|
+
resolved_order = resolve_category_order(category_order, cfg, order_key)
|
|
306
|
+
|
|
307
|
+
with mpl_theme(cfg):
|
|
308
|
+
if ax is None:
|
|
309
|
+
fig, ax = plt.subplots(figsize=figsize or (8.0, 8.5))
|
|
310
|
+
else:
|
|
311
|
+
fig = ax.figure
|
|
312
|
+
|
|
313
|
+
ax.set_facecolor(cfg.theme.axes_facecolor)
|
|
314
|
+
|
|
315
|
+
if boundary is not None:
|
|
316
|
+
poly = (
|
|
317
|
+
read_spatial(boundary, crs=resolved_crs, config=cfg)
|
|
318
|
+
if isinstance(boundary, (str, Path))
|
|
319
|
+
else boundary.to_crs(resolved_crs)
|
|
320
|
+
if getattr(boundary, "crs", None) is not None
|
|
321
|
+
else boundary.set_crs(resolved_crs)
|
|
322
|
+
)
|
|
323
|
+
if boundary_filter_col and boundary_filter_value is not None:
|
|
324
|
+
poly = poly[poly[boundary_filter_col] == boundary_filter_value]
|
|
325
|
+
if len(poly) > 0:
|
|
326
|
+
poly.plot(
|
|
327
|
+
ax=ax,
|
|
328
|
+
facecolor="#ffffff",
|
|
329
|
+
edgecolor=cfg.theme.text_color,
|
|
330
|
+
linewidth=1.4,
|
|
331
|
+
zorder=1,
|
|
332
|
+
)
|
|
333
|
+
|
|
334
|
+
present = set(pts_gdf[resolved_cat].astype(str).unique())
|
|
335
|
+
display_cats = [c for c in resolved_order if c in present] + [
|
|
336
|
+
c for c in sorted(present) if c not in resolved_order
|
|
337
|
+
]
|
|
338
|
+
|
|
339
|
+
marker_map = {"Improving": "^", "Indeterminate": "o", "Degrading": "v"}
|
|
340
|
+
handles: list[Line2D] = []
|
|
341
|
+
|
|
342
|
+
for cat in display_cats:
|
|
343
|
+
sub = pts_gdf[pts_gdf[resolved_cat].astype(str) == cat]
|
|
344
|
+
color = resolved_palette.get(cat, "#999999")
|
|
345
|
+
marker = marker_map.get(cat, "o") if mode == "trend" else "o"
|
|
346
|
+
sub.plot(
|
|
347
|
+
ax=ax,
|
|
348
|
+
color=color,
|
|
349
|
+
edgecolor="#222222",
|
|
350
|
+
linewidth=0.9,
|
|
351
|
+
marker=marker,
|
|
352
|
+
markersize=marker_size,
|
|
353
|
+
zorder=4,
|
|
354
|
+
)
|
|
355
|
+
label = f"Grade {cat}" if (mode == "state" and len(cat) == 1) else cat
|
|
356
|
+
handles.append(
|
|
357
|
+
Line2D(
|
|
358
|
+
[0],
|
|
359
|
+
[0],
|
|
360
|
+
marker=marker,
|
|
361
|
+
color="w",
|
|
362
|
+
label=label,
|
|
363
|
+
markerfacecolor=color,
|
|
364
|
+
markeredgecolor="#222222",
|
|
365
|
+
markersize=9.5,
|
|
366
|
+
)
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
ax.set_aspect("equal")
|
|
370
|
+
ax.set_xticks([])
|
|
371
|
+
ax.set_yticks([])
|
|
372
|
+
for spine in ax.spines.values():
|
|
373
|
+
spine.set_edgecolor(cfg.theme.spine_color)
|
|
374
|
+
spine.set_linewidth(0.8)
|
|
375
|
+
|
|
376
|
+
# North arrow (top-right)
|
|
377
|
+
if show_north_arrow:
|
|
378
|
+
ax.annotate(
|
|
379
|
+
"N",
|
|
380
|
+
xy=(0.95, 0.95),
|
|
381
|
+
xytext=(0.95, 0.87),
|
|
382
|
+
xycoords="axes fraction",
|
|
383
|
+
textcoords="axes fraction",
|
|
384
|
+
ha="center",
|
|
385
|
+
va="center",
|
|
386
|
+
fontsize=11,
|
|
387
|
+
fontweight="bold",
|
|
388
|
+
color=cfg.theme.text_color,
|
|
389
|
+
arrowprops={
|
|
390
|
+
"arrowstyle": "-|>",
|
|
391
|
+
"color": cfg.theme.text_color,
|
|
392
|
+
"lw": 1.6,
|
|
393
|
+
},
|
|
394
|
+
)
|
|
395
|
+
|
|
396
|
+
# Metric scale bar (bottom-left) when projected in metres (e.g., EPSG:2193)
|
|
397
|
+
if show_scale_bar and str(resolved_crs).upper() not in {"EPSG:4326", "4326", "WGS84"}:
|
|
398
|
+
xmin, xmax = ax.get_xlim()
|
|
399
|
+
ymin, ymax = ax.get_ylim()
|
|
400
|
+
width_m = xmax - xmin
|
|
401
|
+
if width_m > 0:
|
|
402
|
+
target_km = max(1, round((width_m * 0.2) / 1000.0 / 5.0) * 5) or 1
|
|
403
|
+
bar_m = target_km * 1000.0
|
|
404
|
+
x0 = xmin + width_m * 0.05
|
|
405
|
+
y0 = ymin + (ymax - ymin) * 0.05
|
|
406
|
+
ax.plot([x0, x0 + bar_m], [y0, y0], color=cfg.theme.text_color, lw=2.5, zorder=6)
|
|
407
|
+
ax.text(
|
|
408
|
+
x0 + bar_m / 2.0,
|
|
409
|
+
y0 + (ymax - ymin) * 0.015,
|
|
410
|
+
f"{target_km} km",
|
|
411
|
+
ha="center",
|
|
412
|
+
va="bottom",
|
|
413
|
+
fontsize=cfg.theme.caption_size,
|
|
414
|
+
color=cfg.theme.text_color,
|
|
415
|
+
fontweight="bold",
|
|
416
|
+
zorder=6,
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
ax.legend(
|
|
420
|
+
handles=handles,
|
|
421
|
+
title=legend_title or default_legend,
|
|
422
|
+
loc="lower right",
|
|
423
|
+
frameon=True,
|
|
424
|
+
facecolor=cfg.theme.background_color,
|
|
425
|
+
edgecolor=cfg.theme.spine_color,
|
|
426
|
+
fontsize=cfg.theme.legend_size,
|
|
427
|
+
title_fontsize=cfg.theme.legend_size,
|
|
428
|
+
)
|
|
429
|
+
|
|
430
|
+
if title:
|
|
431
|
+
ax.set_title(
|
|
432
|
+
title if not subtitle else f"{title}\n{subtitle}",
|
|
433
|
+
fontsize=cfg.theme.title_size,
|
|
434
|
+
fontweight=cfg.theme.title_weight,
|
|
435
|
+
color=cfg.theme.text_color,
|
|
436
|
+
pad=12,
|
|
437
|
+
)
|
|
438
|
+
|
|
439
|
+
return fig, ax
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def publication_map(
|
|
443
|
+
fmu_polygons: Any,
|
|
444
|
+
*,
|
|
445
|
+
context_polygons: Any = None,
|
|
446
|
+
rivers: Any = None,
|
|
447
|
+
towns: pd.DataFrame | None = None,
|
|
448
|
+
sites_df: pd.DataFrame | None = None,
|
|
449
|
+
mode: str = "state",
|
|
450
|
+
fmu_name_col: str | None = None,
|
|
451
|
+
highlight_fmu: str | None = None,
|
|
452
|
+
site_category_col: str | None = None,
|
|
453
|
+
x_col: str | None = None,
|
|
454
|
+
y_col: str | None = None,
|
|
455
|
+
town_name_col: str = "Name",
|
|
456
|
+
town_x_col: str | None = None,
|
|
457
|
+
town_y_col: str | None = None,
|
|
458
|
+
crs: str | int | None = None,
|
|
459
|
+
context_color: str = "#2b3d4f",
|
|
460
|
+
fmu_facecolor: str = "#ffffff",
|
|
461
|
+
highlight_color: str = "#e6f5fa",
|
|
462
|
+
fmu_edgecolor: str = "#263742",
|
|
463
|
+
river_color: str = "#9ecae1",
|
|
464
|
+
town_color: str = "#e74c3c",
|
|
465
|
+
ocean_color: str = "#ffffff",
|
|
466
|
+
palette: dict[str, str] | None = None,
|
|
467
|
+
title: str | None = None,
|
|
468
|
+
subtitle: str | None = None,
|
|
469
|
+
legend_title: str | None = None,
|
|
470
|
+
show_north_arrow: bool = True,
|
|
471
|
+
show_scale_bar: bool = True,
|
|
472
|
+
marker_size: float = 95.0,
|
|
473
|
+
figsize: tuple[float, float] | None = None,
|
|
474
|
+
ax: Any = None,
|
|
475
|
+
config: str | Path | Config | None = None,
|
|
476
|
+
) -> tuple[Any, Any]:
|
|
477
|
+
"""Create a styled editorial/publication static map with high-contrast regional context.
|
|
478
|
+
|
|
479
|
+
Follows the clean Horizons print cartographic style: deep slate neighbouring landmass
|
|
480
|
+
(``context_polygons``), crisp white FMU polygons with dark slate outlines, optional
|
|
481
|
+
pale-blue river network, red town dots with haloed bold labels, and optional site
|
|
482
|
+
monitoring markers (state grades or trend arrows).
|
|
483
|
+
|
|
484
|
+
Returns:
|
|
485
|
+
Tuple of ``(fig, ax)``.
|
|
486
|
+
"""
|
|
487
|
+
try:
|
|
488
|
+
import geopandas as gpd
|
|
489
|
+
except ImportError as exc:
|
|
490
|
+
raise ImportError(
|
|
491
|
+
'Publication maps require geopandas. Install with: pip install "stplot[geo]"'
|
|
492
|
+
) from exc
|
|
493
|
+
|
|
494
|
+
import matplotlib.patheffects as pe
|
|
495
|
+
import matplotlib.pyplot as plt
|
|
496
|
+
from matplotlib.lines import Line2D
|
|
497
|
+
|
|
498
|
+
from stplot.theme.mpl import mpl_theme
|
|
499
|
+
from stplot.transform.filters import derive_trend_direction_3level
|
|
500
|
+
|
|
501
|
+
cfg = ensure_config(config)
|
|
502
|
+
resolved_crs = crs if crs is not None else cfg.columns.get("crs", "EPSG:2193")
|
|
503
|
+
resolved_x = resolve_column(x_col, cfg, "x")
|
|
504
|
+
resolved_y = resolve_column(y_col, cfg, "y")
|
|
505
|
+
|
|
506
|
+
def _load_gdf(src: Any) -> Any:
|
|
507
|
+
if isinstance(src, (str, Path)):
|
|
508
|
+
return read_spatial(src, crs=resolved_crs, config=cfg)
|
|
509
|
+
if getattr(src, "crs", None) is not None:
|
|
510
|
+
return src.to_crs(resolved_crs)
|
|
511
|
+
return src.set_crs(resolved_crs)
|
|
512
|
+
|
|
513
|
+
fmu_gdf = _load_gdf(fmu_polygons)
|
|
514
|
+
minx, miny, maxx, maxy = fmu_gdf.total_bounds
|
|
515
|
+
pad_x = (maxx - minx) * 0.14
|
|
516
|
+
pad_y = (maxy - miny) * 0.08
|
|
517
|
+
|
|
518
|
+
with mpl_theme(cfg):
|
|
519
|
+
if ax is None:
|
|
520
|
+
fig, ax = plt.subplots(figsize=figsize or (8.2, 9.2))
|
|
521
|
+
else:
|
|
522
|
+
fig = ax.figure
|
|
523
|
+
|
|
524
|
+
ax.set_facecolor(ocean_color)
|
|
525
|
+
|
|
526
|
+
# 1. Surrounding neighbouring regions in deep slate navy
|
|
527
|
+
if context_polygons is not None:
|
|
528
|
+
ctx_gdf = _load_gdf(context_polygons)
|
|
529
|
+
ctx_gdf.plot(
|
|
530
|
+
ax=ax,
|
|
531
|
+
facecolor=context_color,
|
|
532
|
+
edgecolor="#3d5166",
|
|
533
|
+
linewidth=0.5,
|
|
534
|
+
zorder=1,
|
|
535
|
+
)
|
|
536
|
+
|
|
537
|
+
# 2. Target FMU polygons in crisp white with dark slate boundaries
|
|
538
|
+
fmu_gdf.plot(
|
|
539
|
+
ax=ax,
|
|
540
|
+
facecolor=fmu_facecolor,
|
|
541
|
+
edgecolor=fmu_edgecolor,
|
|
542
|
+
linewidth=1.6,
|
|
543
|
+
zorder=2,
|
|
544
|
+
)
|
|
545
|
+
if highlight_fmu and fmu_name_col and fmu_name_col in fmu_gdf.columns:
|
|
546
|
+
hl = fmu_gdf[fmu_gdf[fmu_name_col].astype(str) == str(highlight_fmu)]
|
|
547
|
+
if len(hl) > 0:
|
|
548
|
+
hl.plot(
|
|
549
|
+
ax=ax,
|
|
550
|
+
facecolor=highlight_color,
|
|
551
|
+
edgecolor=fmu_edgecolor,
|
|
552
|
+
linewidth=2.0,
|
|
553
|
+
zorder=2.5,
|
|
554
|
+
)
|
|
555
|
+
|
|
556
|
+
# 3. Optional delicate river network
|
|
557
|
+
if rivers is not None:
|
|
558
|
+
riv_gdf = _load_gdf(rivers)
|
|
559
|
+
riv_gdf.plot(ax=ax, color=river_color, linewidth=0.8, alpha=0.9, zorder=3)
|
|
560
|
+
|
|
561
|
+
# 4. Optional reference towns with coral dots and crisp white-haloed labels
|
|
562
|
+
if towns is not None and not towns.empty:
|
|
563
|
+
tx = town_x_col or resolved_x
|
|
564
|
+
ty = town_y_col or resolved_y
|
|
565
|
+
validate_columns(towns, [town_name_col, tx, ty], context="publication_map(towns)")
|
|
566
|
+
ax.scatter(
|
|
567
|
+
towns[tx],
|
|
568
|
+
towns[ty],
|
|
569
|
+
s=32,
|
|
570
|
+
color=town_color,
|
|
571
|
+
edgecolors="none",
|
|
572
|
+
zorder=5,
|
|
573
|
+
)
|
|
574
|
+
label_offset = (maxy - miny) * 0.014
|
|
575
|
+
for _, trow in towns.iterrows():
|
|
576
|
+
ax.text(
|
|
577
|
+
float(trow[tx]),
|
|
578
|
+
float(trow[ty]) + label_offset,
|
|
579
|
+
str(trow[town_name_col]),
|
|
580
|
+
ha="center",
|
|
581
|
+
va="bottom",
|
|
582
|
+
fontsize=cfg.theme.tick_size - 0.8,
|
|
583
|
+
fontweight="bold",
|
|
584
|
+
color="#1a252f",
|
|
585
|
+
path_effects=[pe.withStroke(linewidth=2.8, foreground="#ffffff")],
|
|
586
|
+
zorder=6,
|
|
587
|
+
)
|
|
588
|
+
|
|
589
|
+
# 5. Optional monitoring sites overlay (state or trend)
|
|
590
|
+
handles: list[Line2D] = []
|
|
591
|
+
default_legend = "NOF Grade"
|
|
592
|
+
if sites_df is not None and not sites_df.empty:
|
|
593
|
+
work = sites_df.copy()
|
|
594
|
+
if mode == "trend":
|
|
595
|
+
if site_category_col is not None:
|
|
596
|
+
cat_col = site_category_col
|
|
597
|
+
elif (
|
|
598
|
+
cfg.columns.get("trend_confidence") in work.columns
|
|
599
|
+
or cfg.columns.get("trend_category") in work.columns
|
|
600
|
+
):
|
|
601
|
+
work = derive_trend_direction_3level(
|
|
602
|
+
work, out_col="_stplot_trend_dir", config=cfg
|
|
603
|
+
)
|
|
604
|
+
cat_col = "_stplot_trend_dir"
|
|
605
|
+
else:
|
|
606
|
+
cat_col = resolve_column(None, cfg, "trend_direction")
|
|
607
|
+
pal_key, ord_key, default_legend = (
|
|
608
|
+
"trend_directions",
|
|
609
|
+
"trend_directions",
|
|
610
|
+
"Trend Direction",
|
|
611
|
+
)
|
|
612
|
+
else:
|
|
613
|
+
cat_col = resolve_column(site_category_col, cfg, "state_band")
|
|
614
|
+
pal_key, ord_key, default_legend = "state_bands", "state_bands", "NOF Grade"
|
|
615
|
+
|
|
616
|
+
validate_columns(work, [resolved_x, resolved_y, cat_col], context="publication_map")
|
|
617
|
+
work = work.dropna(subset=[resolved_x, resolved_y, cat_col])
|
|
618
|
+
resolved_pal = resolve_palette(palette, cfg, pal_key)
|
|
619
|
+
resolved_ord = resolve_category_order(None, cfg, ord_key)
|
|
620
|
+
|
|
621
|
+
pts = gpd.GeoDataFrame(
|
|
622
|
+
work,
|
|
623
|
+
geometry=gpd.points_from_xy(work[resolved_x], work[resolved_y]),
|
|
624
|
+
crs=resolved_crs,
|
|
625
|
+
)
|
|
626
|
+
present = set(pts[cat_col].astype(str).unique())
|
|
627
|
+
display_cats = [c for c in resolved_ord if c in present] + [
|
|
628
|
+
c for c in sorted(present) if c not in resolved_ord
|
|
629
|
+
]
|
|
630
|
+
marker_map = {"Improving": "^", "Indeterminate": "o", "Degrading": "v"}
|
|
631
|
+
|
|
632
|
+
for cat in display_cats:
|
|
633
|
+
sub = pts[pts[cat_col].astype(str) == cat]
|
|
634
|
+
color = resolved_pal.get(cat, "#999999")
|
|
635
|
+
marker = marker_map.get(cat, "o") if mode == "trend" else "o"
|
|
636
|
+
sub.plot(
|
|
637
|
+
ax=ax,
|
|
638
|
+
color=color,
|
|
639
|
+
edgecolor="#1a252f",
|
|
640
|
+
linewidth=0.9,
|
|
641
|
+
marker=marker,
|
|
642
|
+
markersize=marker_size,
|
|
643
|
+
zorder=7,
|
|
644
|
+
)
|
|
645
|
+
lbl = f"Grade {cat}" if (mode == "state" and len(cat) == 1) else cat
|
|
646
|
+
handles.append(
|
|
647
|
+
Line2D(
|
|
648
|
+
[0],
|
|
649
|
+
[0],
|
|
650
|
+
marker=marker,
|
|
651
|
+
color="w",
|
|
652
|
+
label=lbl,
|
|
653
|
+
markerfacecolor=color,
|
|
654
|
+
markeredgecolor="#1a252f",
|
|
655
|
+
markersize=9.0,
|
|
656
|
+
)
|
|
657
|
+
)
|
|
658
|
+
|
|
659
|
+
ax.set_xlim(minx - pad_x, maxx + pad_x)
|
|
660
|
+
ax.set_ylim(miny - pad_y, maxy + pad_y)
|
|
661
|
+
ax.set_aspect("equal")
|
|
662
|
+
ax.set_xticks([])
|
|
663
|
+
ax.set_yticks([])
|
|
664
|
+
ax.set_xlabel("")
|
|
665
|
+
ax.set_ylabel("")
|
|
666
|
+
for spine in ax.spines.values():
|
|
667
|
+
spine.set_visible(False)
|
|
668
|
+
|
|
669
|
+
if show_north_arrow:
|
|
670
|
+
ax.annotate(
|
|
671
|
+
"N",
|
|
672
|
+
xy=(0.94, 0.96),
|
|
673
|
+
xytext=(0.94, 0.89),
|
|
674
|
+
xycoords="axes fraction",
|
|
675
|
+
textcoords="axes fraction",
|
|
676
|
+
ha="center",
|
|
677
|
+
va="center",
|
|
678
|
+
fontsize=10.5,
|
|
679
|
+
fontweight="bold",
|
|
680
|
+
color="#1a252f",
|
|
681
|
+
path_effects=[pe.withStroke(linewidth=2.5, foreground="#ffffff")],
|
|
682
|
+
arrowprops={"arrowstyle": "-|>", "color": "#1a252f", "lw": 1.6},
|
|
683
|
+
zorder=8,
|
|
684
|
+
)
|
|
685
|
+
|
|
686
|
+
if show_scale_bar and str(resolved_crs).upper() not in {"EPSG:4326", "4326", "WGS84"}:
|
|
687
|
+
xmin_v, xmax_v = ax.get_xlim()
|
|
688
|
+
ymin_v, ymax_v = ax.get_ylim()
|
|
689
|
+
width_m = xmax_v - xmin_v
|
|
690
|
+
if width_m > 0:
|
|
691
|
+
target_km = max(1, round((width_m * 0.18) / 1000.0 / 5.0) * 5) or 1
|
|
692
|
+
bar_m = target_km * 1000.0
|
|
693
|
+
x0 = xmin_v + width_m * 0.04
|
|
694
|
+
y0 = ymin_v + (ymax_v - ymin_v) * 0.04
|
|
695
|
+
ax.plot(
|
|
696
|
+
[x0, x0 + bar_m],
|
|
697
|
+
[y0, y0],
|
|
698
|
+
color="#1a252f",
|
|
699
|
+
lw=2.6,
|
|
700
|
+
path_effects=[pe.withStroke(linewidth=4.5, foreground="#ffffff")],
|
|
701
|
+
zorder=8,
|
|
702
|
+
)
|
|
703
|
+
ax.text(
|
|
704
|
+
x0 + bar_m / 2.0,
|
|
705
|
+
y0 + (ymax_v - ymin_v) * 0.015,
|
|
706
|
+
f"{target_km} km",
|
|
707
|
+
ha="center",
|
|
708
|
+
va="bottom",
|
|
709
|
+
fontsize=cfg.theme.caption_size,
|
|
710
|
+
fontweight="bold",
|
|
711
|
+
color="#1a252f",
|
|
712
|
+
path_effects=[pe.withStroke(linewidth=2.5, foreground="#ffffff")],
|
|
713
|
+
zorder=8,
|
|
714
|
+
)
|
|
715
|
+
|
|
716
|
+
if handles:
|
|
717
|
+
ax.legend(
|
|
718
|
+
handles=handles,
|
|
719
|
+
title=legend_title or default_legend,
|
|
720
|
+
loc="lower left",
|
|
721
|
+
bbox_to_anchor=(1.02, 0.0),
|
|
722
|
+
frameon=True,
|
|
723
|
+
facecolor="#ffffff",
|
|
724
|
+
edgecolor=cfg.theme.spine_color,
|
|
725
|
+
fontsize=cfg.theme.legend_size,
|
|
726
|
+
title_fontsize=cfg.theme.legend_size,
|
|
727
|
+
)
|
|
728
|
+
|
|
729
|
+
if title:
|
|
730
|
+
ax.set_title(
|
|
731
|
+
title if not subtitle else f"{title}\n{subtitle}",
|
|
732
|
+
fontsize=cfg.theme.title_size,
|
|
733
|
+
fontweight=cfg.theme.title_weight,
|
|
734
|
+
color=cfg.theme.text_color,
|
|
735
|
+
pad=10,
|
|
736
|
+
)
|
|
737
|
+
|
|
738
|
+
return fig, ax
|