Skip to main content

stplot

State and Trends processing and templated plotting helpers in Python.

stplot provides reusable Python functions for preparing pre-computed environmental state and trends results and generating publication-ready, visually consistent plots and maps across multiple plotting backends.

Scope

What stplot IS for

  1. Processing results files — Loading state and trends outputs (primarily CSV/Excel, plus optional shapefiles/GeoPackages or API lookups), standardizing column names, assigning sites to management zones or custom groupings, filtering, aggregating, and reshaping data for visualization.
  2. Templated plotting — Generating standardized static and interactive charts and maps with a consistent visual identity (palettes, category ordering, typography, annotations, and export settings).
  3. Templated reporting (planned) — Populating Word (.docx) report templates with pre-filled figures, captions, and summary tables so new regional/annual reports can be generated quickly and consistently.

What stplot is NOT for

  • Calculating state or trends — Statistical calculations (e.g., percentiles, attribute grading/band assignment from raw time series, Mann-Kendall tests, Sen slopes) are performed upstream by dedicated tools. stplot consumes those results files.

Key Design Principles

  • Hybrid configuration: Project defaults (column name mappings, semantic color palettes, category orderings, typography, and figure dimensions) live in a YAML configuration file, while any function parameter can override those defaults at call time.
  • No hardcoded schemas: Functions accept column mappings via config or explicit keyword arguments so different upstream result formats work without rewriting plotting code.
  • Consistent look across backends: Shared theme tokens (colors, fonts, labels, legend layouts) are translated into backend-specific templates for:
    • Static charts: matplotlib, seaborn
    • Interactive charts: plotly
    • Static & interactive maps: geopandas, folium
  • Composable transforms: Preprocessing steps (zone assignment, grouping, renaming, category ordering) are pure, non-mutating functions that return tidy pandas.DataFrame / geopandas.GeoDataFrame objects ready for any plot template.

Planned Project Structure

stplot/
├── AGENTS.md                 # Guidelines for AI coding agents
├── README.md
├── pyproject.toml            # Package metadata, dependencies, and tool config
├── configs/
│   └── default.yaml          # Default column mappings, palettes, and plot templates
├── src/
│   └── stplot/
│       ├── __init__.py
│       ├── config/           # Config schema, YAML loader, and override resolution
│       ├── io/               # Readers for CSV/Excel, shapefiles/GeoPackage, and APIs
│       ├── transform/        # Zone assignment, site grouping, filtering, reshaping
│       ├── theme/            # Shared palettes, typography, and backend theme adapters
│       ├── plots/            # Templated plot & map functions (static, interactive, geo)
│       └── reporting/        # (Planned) Templated Word (.docx) report assembly
├── tests/                    # Pytest unit and smoke tests using synthetic fixtures
└── examples/                 # Example configs, notebooks, and scripts

Configuration Model (Hybrid & Multi-Preset)

stplot ships with built-in YAML presets in configs/ (and packaged in stplot.config.presets):

  • default / npsfm_lawa (configs/default.yaml) — NZ NPS-FM / LAWA state bands (NOF_Grade: A–E) and IPCC/LWP trend likelihoods (DirectionConf, Improving_Confidence, AnnualSenSlope), NZTM coordinates (NZTM.X, NZTM.Y, EPSG:2193), and FMU/subzone groupings.
  • horizons_one_plan (configs/horizons_one_plan.yaml) — Horizons One Plan compliance reporting (Site.Name, VarName, CriteriaName, SitePasses, nOK, Water.management.subzone.One.Plan).
name: "npsfm_lawa"
columns:
  site_id: "sID"
  indicator: "npID"
  state_band: "NOF_Grade"
  trend_confidence: "DirectionConf"
  zone: "Freshwater.Management.Unit.FMU"
  x: "NZTM.X"
  y: "NZTM.Y"

Every processing and plotting function accepts an optional config (a preset name, YAML/TOML path, or Config object) plus explicit keyword overrides (e.g., group_col="CatName", band_col="NOF_Grade"), resolving values in the order:

  1. Explicit function argument
  2. User-provided YAML/TOML config or named preset
  3. Built-in stplot default (npsfm_lawa)

Usage Example

import stplot as stp

# Load a built-in preset ("npsfm_lawa" or "horizons_one_plan") or a custom YAML/TOML file
cfg = stp.load_config("npsfm_lawa")

# 1. Load and preprocess results
df = stp.io.read_results("data/NPSFM_State_Example.csv")
df = stp.transform.order_categories(df, config=cfg)

# 2. Generate templated plots (with optional per-call overrides)
fig, ax = stp.plots.state_band_bar(
    df,
    group_col="Freshwater.Management.Unit.FMU",  # overrides config.columns["zone"] if needed
    title="NPS-FM State by FMU",
    config=cfg,
)
stp.plots.save_figure(fig, "outputs/state_by_fmu.png", config=cfg)

Implemented Transforms & Plot Templates

Pre-Analysis (stplot.transform)

  • filter_sites(...) — Filter by site_type (River/Lake/Beach/Estuary), status (RepSite/Impact), fmu, catchment, zone, indicator, attribute, period, and valid_only=True (FilterOK or nOK == "OK").
  • split_by_site_group(...) — Split results into separate DataFrames by site status or site type.
  • split_full_and_preliminary(...) & audit_results_data(...) — Split full (FilterOK=True / nOK="OK") vs preliminary/insufficient results without silently dropping records, and run pre-flight QA checks (duplicates, missing coords/FMUs, unmapped indicators).
  • merge_state_and_trends(...) & stplot.io.merge_period_files(...) / combine_period_dataframes(...) — Join separate State & Trends tables (filtering to a target trend_period) and stack multiple historical period Excel/CSV files (e.g., One Plan 2015–2020, 2020–2025) with automatic filename period extraction.
  • derive_pass_fail(...) — Derive "Pass" / "Fail" / "Insufficient data" labels from One Plan SitePasses + nOK.
  • derive_trend_direction_3level(...) — Collapse IPCC/LWP 9-level confidence into "Improving" / "Indeterminate" / "Degrading".
  • build_fmu_vs_region_table(...) — Build "XX.X% (n)" FMU vs Whole Region summary tables.
  • assign_zones(...) & assign_zones_spatial(...) — Assign sites to FMUs/zones via lookup table or geopandas spatial join (with optional nearest-boundary snapping).
  • override_site_zones(...) — Manually assign or correct specific sites whose coordinates fall slightly outside a boundary or into the wrong FMU.
  • pair_upstream_downstream(...) — Pair long-format u/s and d/s records into wide format for paired discharge plots.
  • order_categories(...), summarise_by_group(...), standardize_columns(...).

Plot, Map & Table Templates (stplot.plots)

  • state_band_bar(...) (matplotlib) — Stacked state band counts or percentages by FMU/zone.
  • pass_fail_bar(...) (matplotlib) — Horizons One Plan 100% stacked Pass/Fail bars by variable with n = XX totals and in-bar % labels.
  • pass_fail_donuts(...) (matplotlib) — Small-multiple Pass/Fail donut grid with wrapped center labels and callouts.
  • compliance_dot_matrix(...) (matplotlib) — Site × Indicator compliance dot matrix encoding Pass/Fail and Final/Interim.
  • horizontal_proportion_bar(...) (matplotlib) — Sorted horizontal 100% stacked bar with (n = XX) labels (e.g., recreational swim traffic-light).
  • barbell_plot(...) & multi_node_barbell(...) (matplotlib) — 2-node and multi-node over-time horizontal barbells.
  • slopegraph(...) (matplotlib) — 2-period before/after slopegraph showing value and rank shifts.
  • state_distribution_plot(...) (matplotlib / seaborn) — Box + strip distributions across FMUs overlaid on pastel NOF band shading.
  • trend_diverging_bar(...) (matplotlib) — LAWA-style diverging trend stacked bars around 0%.
  • state_trend_quadrant(...) (matplotlib) — 4-quadrant State vs Trend management prioritization scatter.
  • state_lollipop(...) (plotly) — Sorted horizontal state value lollipop colored by NOF_Grade.
  • trend_lollipop(...) (plotly) — Diverging horizontal trend lollipop (Percent.annual.change) colored by 3-level trend direction.
  • upstream_downstream_comparison(...) (matplotlib) — Paired Upstream (▲) vs Downstream (▼) log-scale comparison grouped by district with NOF grades inside markers.
  • upstream_downstream_timeseries(...) (matplotlib) — Rolling-period Upstream vs Downstream time series with pastel NOF band shading.
  • fmu_state_map(...) (folium) — Interactive Esri greyscale map with automatic NZTM (EPSG:2193) → WGS84 reprojection, optional FMU boundary overlay, grade-colored markers, title badge, and legend.
  • static_fmu_map(...) (geopandas / matplotlib) — 300-DPI static publication map (state circles or trend triangles) with north arrow and km scale bar.
  • grade_matrix(...) (plotly) — Single-site or side-by-side faceted tile grid of NOF grades across attributes and rolling 5-year periods.
  • trend_timeseries(...) (plotly) — Monitoring time series (with censored markers) overlaid with pre-computed Sen slope and CI lines.
  • grade_summary_over_time(...) (plotly) — 100% stacked NOF grade proportions across rolling periods with total site counts above bars.
  • state_over_time(...) & state_over_time_comparison(...) (plotly) — Single-site or multi-site rolling 5-year state trajectory over pastel NOF band zones with grade letters inside contrasting triangle markers (▲ / ▼).
  • style_summary_table(...) (pandas.Styler) — Semantic color-coded FMU vs Whole Region HTML summary tables.
  • publication_map(...), kpi_summary_cards(...), grade_transition_sankey(...), fmu_indicator_heatmap(...), fmu_factsheet_panel(...) — Editorial map and executive reporting templates.
  • catchment_profile_infographic(...), site_report_card(...), catchment_report_card(...), waffle_infographic(...), target_gauge_strip(...), regional_infographic_poster(...) — Publication-ready infographic & report card templates.
  • ecosystem_flower_plot(...), water_quality_stripes(...), bullet_scorecard(...), beeswarm_nof_plot(...), rank_bump_chart(...), swim_season_calendar(...), intervention_spotlight_card(...) — Waterway flower/petal plots, river quality stripes, multi-metric bullet scorecards, NOF beeswarms, FMU rank bump charts, swim-season calendars, and intervention spotlight cards.
  • state_trend_butterfly(...), state_trend_lollipop(...), state_trend_map(...), state_trend_risk_matrix(...), state_trend_heatmap(...), state_trend_sparktable(...) — Combined State + Trend templates (paired butterfly, velocity-arrow lollipop, color+shape map, 2D risk triage matrix, state+trend overlay heatmap, and sparkline summary table).
  • domain_summary_strip(...), discharge_impact_card(...), lake_health_card(...), estuary_coastal_card(...) — Multi-domain reporting cards covering Rivers (SoE/Impact), Lakes (TLI), Estuaries, Coastal Bathing, and Consented Discharges.
  • save_figure(...) & batch_export_by_group(...) — Unified export helpers for Matplotlib, Plotly, and Folium outputs.

Word & HTML Report Assembly (stplot.reporting)

  • create_npsfm_report_template(...) & create_one_plan_report_template(...) — Production A4 Word (.docx) templates with Cover Page, Executive Summary, Regional Multi-Domain chapters (Rivers SoE/Impact, Lakes, Estuaries, Coastal, Discharges), dynamic {%p for fmu in fmus %} FMU/WMS chapters, and Appendices.
  • render_docx_report(...) (docxtpl / python-docx) — Populate a Word (.docx) template with Jinja text variables, top-level & nested per-FMU PNG figures, and styled summary tables.
  • add_styled_table(...) (python-docx) — Append color-coded FMU vs Whole Region summary tables with semantic hex cell shading.
  • build_html_companion(...) — Build a self-contained, tabbed interactive HTML Companion Pack bundling folium maps, plotly charts, base64-inlined PNGs, QA tables, and separated Preliminary results.
  • CaptionTracker & generate_figure_caption(...) — Automated sequential Figure/Table captions with macron-aware label resolution and data-derived site & preliminary counts.
  • build_network_summary_table(...), build_data_sufficiency_table(...), build_indicator_coverage_table(...), build_exceedance_watchlist_table(...), build_site_master_table(...), build_grade_change_table(...), build_top_movers_table(...), select_top_bottom_sites(...) (stplot.transform) — Monitoring network, data sufficiency, exceedance watchlist, site master appendix, grade shift, top movers, and Best/Worst N site selectors.
  • top_bottom_sites_plot(...) (stplot.plots) — Best N & Worst N sites spotlight plot with Regional/FMU Median reference line and auto-detected indicator polarity.

Browse runnable scripts and rendered plot previews in the Examples Gallery.


Getting Started (Setup)

stplot uses a standard src/ layout with pyproject.toml, managed with uv (recommended) or pip.

# Create virtual environment and install in editable mode with dev dependencies
uv venv
uv pip install -e ".[dev]"

# Install optional geospatial and interactive plotting extras
uv pip install -e ".[geo,interactive,dev]"

Using pip

python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
pip install -e ".[dev]"

Development Workflow

Once scaffolding is in place:

  • Run tests: pytest
  • Lint & format: ruff check . and ruff format .
  • Adding a new plot template:
    1. Reuse theme tokens from stplot.theme rather than hardcoding colors or fonts.
    2. Resolve all column names through stplot.config with keyword-argument override support.
    3. Add unit/smoke tests in tests/ using small synthetic DataFrames (no private data files).
    4. Document expected columns and return type in the function docstring.

Metadata

Release files for stplot 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for stplot 0.1.0
File Size Uploaded Provenance Actions
stplot-0.1.0.tar.gz 263.9 kB With provenance Details for stplot-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for stplot 0.1.0
File Interpreter ABI Platform Actions
stplot-0.1.0-py3-none-any.whl Python 3 none any Details for stplot-0.1.0-py3-none-any.whl

Total release size: 421.2 kB

Release files / stplot-0.1.0.tar.gz

Download URL stplot-0.1.0.tar.gz
Size 263.9 kB
Tags Source
SHA-256 checksum
How to use checksums
c6610e9c647f18776d1b0349d1c4d294876c2a0a85433fa328d332d2d69654b1
BLAKE2b-256 checksum
How to use checksums
1d3abc1df092684014e5ee8f27470386c79cd80907eb65aef7179ba05ca7a270
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

Release files / stplot-0.1.0-py3-none-any.whl

Download URL stplot-0.1.0-py3-none-any.whl
Size 157.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
85bcf23fbf9145bbb5706820b7f816b9c21e27c39b4e70da1ffe5ed3b972ec7c
BLAKE2b-256 checksum
How to use checksums
2c14e405289467a6e0a37d3fba6c1075b514a9d91b45d4a7b72ed83473942c61
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

Security for stplot 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for stplot-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page