Worked Examples

Develop and test uncertainty displays — Visualization & Graphing

Develop and test uncertainty displays — Visualization & Graphing Cross-application area: Visualization & Graphing Status: Initial scientific graphics guidance; platform-specific features not verified. Rendering contract objective

ProductSustainable Catalyst Research LabUpdatedNovember 14, 2026Reading time17 minutes

Application area: Visualization & Graphing
Article classification: Development and testing / Scientific rendering contracts / Uncertainty visualization
Audience: Scientific software engineers, visualization developers, researchers, QA engineers, data stewards, and technical reviewers
Technical level: Advanced
Reference environment: Python 3, NumPy, SciPy, Matplotlib, and pytest
Scientific methods: Descriptive variability, Student-t confidence intervals, Student-t prediction intervals, and measurement-uncertainty representation
Primary outputs: Typed rendering contract, validated uncertainty records, deterministic figure artifacts, automated test receipts, and scientific release evidence
Estimated reading time: 15–19 minutes, excluding practical exercises

1. Engineering objective

Scientific uncertainty displays translate numerical observations, derived statistics, and uncertainty estimates into graphical marks.

An implementation must preserve the scientific meaning of the supplied uncertainty rather than treating every interval as a generic graphical error bar.

The central engineering objective is to establish a reproducible, renderer-independent relationship among:

  1. Authoritative input data.
  2. Measurement units and observation identifiers.
  3. Statistical or metrological methods.
  4. Calculated uncertainty values.
  5. Graphical mark coordinates.
  6. Figure labels and captions.
  7. Exported artifacts and provenance.

Primary acceptance condition: Readers must be able to distinguish confidence intervals, prediction intervals, measurement uncertainty, and observed variability; every displayed bound must reconcile with a validated numerical value and an explicit uncertainty definition.

Successful rendering alone is not sufficient evidence of correctness.

2. Establish the rendering contract

A useful uncertainty-rendering contract should separate scientific computation from graphical representation.

Authoritative source artifact
           |
           v
Source schema and rights validation
           |
           v
Statistical or measurement model
           |
           v
Validated uncertainty result
           |
           v
Renderer-independent mark specification
           |
           v
Plotly / Matplotlib / Vega-Lite / other renderer
           |
           v
Figure, numerical table, and evidence manifest
           |
           v
Independent validation and review

Each transition should have an explicit data contract and defined failure behavior.

2.1 Numerical layer

The numerical layer should calculate or retrieve estimates and interval bounds using a documented method.

It should not depend on figure dimensions, pixel positions, or the selected rendering engine.

2.2 Rendering layer

The rendering layer should transform validated numerical values into graphical positions and marks.

It must not silently recalculate, replace, truncate, or reinterpret the underlying statistics.

2.3 Presentation layer

The presentation layer should identify the uncertainty type, units, statistical assumptions, sample counts, and relevant limitations.

A default caption such as “Error bars represent uncertainty” is inadequate when the actual interval type is known.

3. Define typed uncertainty records

A renderer-independent uncertainty record should distinguish raw observations, estimates, interval bounds, and uncertainty metadata.

Table 1. Recommended uncertainty-data contract
Field Purpose Validation
source_artifact_id Identifies the authoritative input Nonempty and resolvable
source_revision Identifies immutable data version Matches source artifact
record_ids Identifies contributing observations Correct contributor membership
uncertainty_type Defines scientific interval meaning Supported explicit enumeration
estimate Central numerical value Finite and method-consistent
lower Lower interval endpoint Finite and not greater than upper
upper Upper interval endpoint Finite and not less than lower
interval_level Nominal confidence or prediction level where applicable Strictly between zero and one
sample_size Number of contributing observations Consistent with calculation
units Physical or statistical units Compatible across displayed quantities
method_id Calculation and assumptions Recognized and versioned
axis_reference Temporal, spatial, or categorical coordinates Correct coordinate semantics
review_status Validation and approval state Not inferred from rendering success

Where the uncertainty distribution is asymmetric, the record must preserve distinct lower and upper extents.

Where the full probability distribution is important, retaining only two interval endpoints may be insufficient.

4. Distinguish uncertainty types in code

The implementation should use explicit names rather than a single ambiguous error field.

Table 2. Scientific meaning of supported uncertainty types
Type Meaning Required caution
observed_variability Spread of observed measurements Not automatically uncertainty about the mean
standard_deviation Descriptive dispersion Requires definition of population or sample calculation
standard_error Estimated sampling variability of a statistic Depends on sampling structure
confidence_interval Interval for a population parameter under a stated procedure Requires statistical method and coverage level
prediction_interval Interval for future observation or outcome under a model Requires predictive target and assumptions
measurement_uncertainty Uncertainty associated with a measurement result Requires metrological definition and coverage semantics
model_ensemble Spread or distribution among model outputs Not automatically a calibrated probability interval

Do not automatically transform a standard deviation into a nominal confidence interval or interpret an ensemble range as a prediction interval.

5. Validate mathematical and statistical assumptions

For an independent sample of n observations, the arithmetic mean is:

mean = sum(x_i) / n

The conventional sample standard deviation is:

s = sqrt(
    sum((x_i - mean)^2) / (n - 1)
)

For an independent, identically distributed sample with finite variance, the conventional standard error of the mean is:

SE = s / sqrt(n)

5.1 Confidence interval for a mean

For an appropriate normally distributed independent-sample model with unknown variance:

CI = mean ± t_critical * s / sqrt(n)

The critical value depends on the selected confidence level and n − 1 degrees of freedom.

5.2 Prediction interval for one future observation

Under the corresponding model:

PI = mean ± t_critical * s * sqrt(1 + 1/n)

This interval is generally wider than the confidence interval for the population mean because it includes expected variation in a future individual observation.

5.3 Measurement uncertainty

For an affine unit conversion:

y = a*x + b

the standard uncertainty transforms as:

u_y = |a| * u_x

when a and b are exact constants and the stated uncertainty model supports this transformation.

Measurement uncertainty may involve additional components, covariance, calibration effects, and nonlinear propagation that require a more complete uncertainty model.

6. Validate interval geometry

For a conventional central-estimate interval:

lower <= estimate <= upper

The graphical extents above and below the estimate are:

lower_error = estimate - lower

upper_error = upper - estimate

Both must be nonnegative.

Do not assume that every uncertainty representation is symmetric or that every scientifically valid interval must contain a designated central estimate. For example, some credible or highest-density intervals may require different handling.

When using a conventional error-bar representation, the implementation should explicitly validate that its numerical geometry satisfies the selected contract.

7. Create a golden synthetic fixture

Use a small deterministic dataset that permits independent numerical verification.

Table 3. Golden reference observations
Record Group Response (synthetic units)
C01 Control 8
C02 Control 9
C03 Control 10
C04 Control 11
C05 Control 12
T01 Treatment 11
T02 Treatment 12
T03 Treatment 13
T04 Treatment 14
T05 Treatment 15

Expected reference properties:

Control:
n = 5
mean = 10

Treatment:
n = 5
mean = 13

Both:
sample standard deviation = sqrt(2.5)
standard error = sqrt(0.5)

Prediction intervals:
Wider than corresponding confidence intervals

These values are synthetic. The statistical interval calculations assume independent observations sampled from normal populations, with unknown population variances.

The fixture does not establish the suitability of those assumptions for a real dataset.

8. Prepare the development environment

mkdir uncertainty-renderer-tests
cd uncertainty-renderer-tests

python3 -m venv .venv
source .venv/bin/activate

python -m pip install numpy scipy matplotlib pytest

python --version
python -m pip freeze > requirements-lock.txt

Retain the resulting dependency file with the test evidence. For production or formally reproducible research, use a reviewed dependency-locking and environment-verification process.

9. Implement the numerical and rendering contract

Save as uncertainty_contract.py.

from dataclasses import dataclass
from enum import Enum
import math

import numpy as np
from scipy.stats import t


class UncertaintyType(str, Enum):
    CONFIDENCE = "confidence_interval"
    PREDICTION = "prediction_interval"
    MEASUREMENT = "measurement_uncertainty"


@dataclass(frozen=True)
class IntervalMark:
    source_id: str
    group: str
    uncertainty_type: UncertaintyType
    estimate: float
    lower: float
    upper: float
    units: str
    method_id: str
    sample_size: int | None
    interval_level: float | None
    record_ids: tuple[str, ...]


def validate_mark(mark):
    if not isinstance(
        mark.uncertainty_type,
        UncertaintyType
    ):
        raise ValueError(
            "Invalid uncertainty type"
        )

    if not mark.source_id.strip():
        raise ValueError("Missing source identity")

    if not mark.group.strip():
        raise ValueError("Missing group")

    if not mark.units.strip():
        raise ValueError("Missing units")

    if not mark.method_id.strip():
        raise ValueError("Missing method ID")

    values = (
        mark.estimate,
        mark.lower,
        mark.upper
    )

    if not all(
        math.isfinite(value)
        for value in values
    ):
        raise ValueError("Nonfinite interval value")

    if not (
        mark.lower
        <= mark.estimate
        <= mark.upper
    ):
        raise ValueError(
            "Invalid interval geometry"
        )

    if mark.sample_size is not None:
        if (
            isinstance(mark.sample_size, bool)
            or not isinstance(mark.sample_size, int)
            or mark.sample_size < 1
        ):
            raise ValueError("Invalid sample size")

    if mark.interval_level is not None:
        if not (
            math.isfinite(mark.interval_level)
            and 0 < mark.interval_level < 1
        ):
            raise ValueError(
                "Invalid interval level"
            )

    if mark.uncertainty_type in (
        UncertaintyType.CONFIDENCE,
        UncertaintyType.PREDICTION
    ):
        if mark.sample_size is None or (
            mark.sample_size < 2
        ):
            raise ValueError(
                "Insufficient sample size"
            )

        if mark.interval_level is None:
            raise ValueError(
                "Missing confidence or prediction level"
            )

        if len(mark.record_ids) != mark.sample_size:
            raise ValueError(
                "Contributor count mismatch"
            )

    if len(set(mark.record_ids)) != len(
        mark.record_ids
    ):
        raise ValueError(
            "Duplicate contributor IDs"
        )

    return True


def student_t_intervals(
    values,
    record_ids,
    group,
    source_id,
    units="synthetic units",
    level=0.95
):
    data = np.asarray(
        values,
        dtype=float
    )

    if data.ndim != 1 or data.size < 2:
        raise ValueError(
            "At least two observations required"
        )

    if not np.isfinite(data).all():
        raise ValueError(
            "Invalid numerical source"
        )

    if not 0 < level < 1:
        raise ValueError(
            "Invalid interval level"
        )

    ids = tuple(record_ids)

    if len(ids) != len(data):
        raise ValueError(
            "Source record count mismatch"
        )

    n = len(data)
    mean = float(np.mean(data))
    sd = float(np.std(data, ddof=1))

    critical = float(
        t.ppf(
            (1 + level) / 2,
            df=n - 1
        )
    )

    ci_half = critical * sd / math.sqrt(n)

    pi_half = (
        critical
        * sd
        * math.sqrt(1 + 1 / n)
    )

    common = {
        "source_id": source_id,
        "group": group,
        "estimate": mean,
        "units": units,
        "sample_size": n,
        "interval_level": level,
        "record_ids": ids
    }

    confidence = IntervalMark(
        uncertainty_type=UncertaintyType.CONFIDENCE,
        lower=mean - ci_half,
        upper=mean + ci_half,
        method_id="student_t_mean_ci_v1",
        **common
    )

    prediction = IntervalMark(
        uncertainty_type=UncertaintyType.PREDICTION,
        lower=mean - pi_half,
        upper=mean + pi_half,
        method_id="student_t_single_observation_pi_v1",
        **common
    )

    validate_mark(confidence)
    validate_mark(prediction)

    return confidence, prediction


def measurement_interval(
    value,
    expanded_uncertainty,
    source_id,
    group,
    units,
    method_id
):
    if not (
        math.isfinite(value)
        and math.isfinite(expanded_uncertainty)
    ):
        raise ValueError(
            "Invalid measurement parameters"
        )

    if expanded_uncertainty < 0:
        raise ValueError(
            "Negative expanded uncertainty"
        )

    mark = IntervalMark(
        source_id=source_id,
        group=group,
        uncertainty_type=(
            UncertaintyType.MEASUREMENT
        ),
        estimate=value,
        lower=value - expanded_uncertainty,
        upper=value + expanded_uncertainty,
        units=units,
        method_id=method_id,
        sample_size=None,
        interval_level=None,
        record_ids=()
    )

    validate_mark(mark)
    return mark


def error_extents(mark):
    validate_mark(mark)

    return (
        mark.estimate - mark.lower,
        mark.upper - mark.estimate
    )

The contract intentionally requires an explicit uncertainty type and method identifier.

Measurement uncertainty uses a separate constructor because its metrological interpretation does not necessarily involve a statistical sample size or a Student-t interval.

The measurement constructor assumes a supplied symmetric expanded uncertainty. Real measurement-uncertainty procedures may be asymmetric and may require additional metadata, including coverage factor and uncertainty-budget references.

10. Implement the reference renderer

The renderer should accept validated marks without recalculating their statistical meaning.

Save as render_uncertainty_contract.py.

from dataclasses import asdict
from pathlib import Path
import hashlib
import json

import matplotlib
matplotlib.use("Agg")

import matplotlib.pyplot as plt
import numpy as np

from uncertainty_contract import (
    UncertaintyType,
    student_t_intervals,
    validate_mark,
    error_extents
)


OUTPUT = Path("renderer-output")


def sha256_file(path):
    digest = hashlib.sha256()

    with Path(path).open("rb") as handle:
        for block in iter(
            lambda: handle.read(1024 * 1024),
            b""
        ):
            digest.update(block)

    return digest.hexdigest()


def build_fixture():
    control = np.array(
        [8., 9., 10., 11., 12.]
    )

    treatment = np.array(
        [11., 12., 13., 14., 15.]
    )

    control_ci, control_pi = student_t_intervals(
        control,
        ("C01", "C02", "C03", "C04", "C05"),
        "Control",
        "synthetic-fixture-v1"
    )

    treatment_ci, treatment_pi = (
        student_t_intervals(
            treatment,
            ("T01", "T02", "T03", "T04", "T05"),
            "Treatment",
            "synthetic-fixture-v1"
        )
    )

    return [
        control_ci,
        treatment_ci,
        control_pi,
        treatment_pi
    ]


def render_marks(marks, filename):
    if not marks:
        raise ValueError(
            "No marks supplied"
        )

    for mark in marks:
        validate_mark(mark)

    types = {
        mark.uncertainty_type
        for mark in marks
    }

    if len(types) != 1:
        raise ValueError(
            "Mixed uncertainty types require "
            "separate explicitly labeled rendering"
        )

    units = {mark.units for mark in marks}

    if len(units) != 1:
        raise ValueError(
            "Mixed units on one axis"
        )

    interval_type = next(iter(types))

    fig, ax = plt.subplots(
        figsize=(7, 4.5),
        dpi=160
    )

    for index, mark in enumerate(marks):
        lower_error, upper_error = (
            error_extents(mark)
        )

        ax.errorbar(
            x=index,
            y=mark.estimate,
            yerr=[
                [lower_error],
                [upper_error]
            ],
            fmt="o" if index == 0 else "s",
            capsize=6,
            markersize=8
        )

    labels = [
        mark.group
        for mark in marks
    ]

    ax.set_xticks(
        range(len(marks)),
        labels
    )

    ax.set_ylabel(
        f"Response ({next(iter(units))})"
    )

    if interval_type == UncertaintyType.CONFIDENCE:
        title = "95% confidence intervals for means"
    elif interval_type == UncertaintyType.PREDICTION:
        title = "95% prediction intervals"
    else:
        title = "Measurement uncertainty"

    ax.set_title(title)

    minimum = min(
        mark.lower for mark in marks
    )

    maximum = max(
        mark.upper for mark in marks
    )

    margin = max(
        (maximum - minimum) * 0.1,
        0.5
    )

    ax.set_ylim(
        minimum - margin,
        maximum + margin
    )

    fig.tight_layout()

    path = OUTPUT / filename
    fig.savefig(path)
    plt.close(fig)

    return path


def main():
    OUTPUT.mkdir(exist_ok=True)

    marks = build_fixture()

    confidence = [
        mark for mark in marks
        if mark.uncertainty_type
        == UncertaintyType.CONFIDENCE
    ]

    prediction = [
        mark for mark in marks
        if mark.uncertainty_type
        == UncertaintyType.PREDICTION
    ]

    confidence_path = render_marks(
        confidence,
        "confidence-intervals.png"
    )

    prediction_path = render_marks(
        prediction,
        "prediction-intervals.png"
    )

    serialized_marks = []

    for mark in marks:
        data = asdict(mark)
        data["uncertainty_type"] = (
            mark.uncertainty_type.value
        )
        serialized_marks.append(data)

    report = {
        "classification": "synthetic",
        "source_id": "synthetic-fixture-v1",
        "marks": serialized_marks,
        "artifacts": {
            "confidence_sha256": sha256_file(
                confidence_path
            ),
            "prediction_sha256": sha256_file(
                prediction_path
            )
        },
        "numerical_validation": "not_tested",
        "visual_review": "not_tested",
        "accessibility": "not_tested",
        "security": "not_tested",
        "scientific_review": "not_tested"
    }

    (OUTPUT / "report.json").write_text(
        json.dumps(report, indent=2),
        encoding="utf-8"
    )

    print("Generated validated-mark figures")


if __name__ == "__main__":
    main()

The example rejects mixed uncertainty types on a single rendering call, rather than silently combining confidence and prediction intervals under an ambiguous title.

This is a conservative educational policy, not a universal prohibition. A production renderer may display different uncertainty types together if each is clearly distinguished through labels, marks, legends, and accessible equivalents.

11. Execute the reference renderer

python render_uncertainty_contract.py

Expected output:

Generated validated-mark figures

Generated artifacts:

renderer-output/
  confidence-intervals.png
  prediction-intervals.png
  report.json

The figures should show the means of the two synthetic groups, with interval extents calculated independently of the rendering code.

The report preserves the numerical interval definitions and figure hashes.

Figure hashes support artifact identity but do not establish numerical or scientific correctness by themselves.

12. Implement golden and negative tests

Automated testing should verify correct calculations and reject invalid uncertainty records before rendering.

Save as test_uncertainty_contract.py.

from dataclasses import replace
import math

import numpy as np
import pytest

from uncertainty_contract import (
    IntervalMark,
    UncertaintyType,
    student_t_intervals,
    measurement_interval,
    validate_mark,
    error_extents
)


def fixture():
    return student_t_intervals(
        [8., 9., 10., 11., 12.],
        ("C01", "C02", "C03", "C04", "C05"),
        "Control",
        "synthetic-fixture-v1"
    )


def test_golden_mean():
    ci, pi = fixture()

    assert ci.estimate == 10.0
    assert pi.estimate == 10.0


def test_confidence_interval_bounds():
    ci, _ = fixture()

    assert ci.lower == pytest.approx(
        8.0367568,
        abs=1e-6
    )

    assert ci.upper == pytest.approx(
        11.9632432,
        abs=1e-6
    )


def test_prediction_interval_wider():
    ci, pi = fixture()

    assert (
        pi.upper - pi.lower
        > ci.upper - ci.lower
    )


def test_explicit_uncertainty_types():
    ci, pi = fixture()

    assert ci.uncertainty_type == (
        UncertaintyType.CONFIDENCE
    )

    assert pi.uncertainty_type == (
        UncertaintyType.PREDICTION
    )


def test_error_extents():
    ci, _ = fixture()

    lower, upper = error_extents(ci)

    assert lower >= 0
    assert upper >= 0

    assert lower == pytest.approx(upper)


def test_invalid_interval_order():
    ci, _ = fixture()

    broken = replace(
        ci,
        lower=12.,
        upper=8.
    )

    with pytest.raises(ValueError):
        validate_mark(broken)


def test_nonfinite_interval():
    ci, _ = fixture()

    broken = replace(
        ci,
        upper=math.inf
    )

    with pytest.raises(ValueError):
        validate_mark(broken)


def test_missing_units():
    ci, _ = fixture()

    broken = replace(ci, units="")

    with pytest.raises(ValueError):
        validate_mark(broken)


def test_missing_source_id():
    ci, _ = fixture()

    broken = replace(ci, source_id="")

    with pytest.raises(ValueError):
        validate_mark(broken)


def test_invalid_confidence_level():
    ci, _ = fixture()

    broken = replace(
        ci,
        interval_level=1.0
    )

    with pytest.raises(ValueError):
        validate_mark(broken)


def test_contributor_count_mismatch():
    ci, _ = fixture()

    broken = replace(
        ci,
        record_ids=("C01", "C02")
    )

    with pytest.raises(ValueError):
        validate_mark(broken)


def test_duplicate_contributors():
    ci, _ = fixture()

    broken = replace(
        ci,
        record_ids=(
            "C01", "C01", "C03",
            "C04", "C05"
        )
    )

    with pytest.raises(ValueError):
        validate_mark(broken)


def test_single_observation_rejected():
    with pytest.raises(ValueError):
        student_t_intervals(
            [10.],
            ("C01",),
            "Control",
            "synthetic-fixture-v1"
        )


@pytest.mark.parametrize(
    "invalid",
    [np.nan, np.inf, -np.inf]
)
def test_nonfinite_source_rejected(invalid):
    with pytest.raises(ValueError):
        student_t_intervals(
            [8., invalid, 10.],
            ("C01", "C02", "C03"),
            "Control",
            "synthetic-fixture-v1"
        )


def test_measurement_uncertainty():
    mark = measurement_interval(
        value=1000.,
        expanded_uncertainty=20.,
        source_id="synthetic-measurement",
        group="Sample A",
        units="g",
        method_id="synthetic-expanded-u"
    )

    assert mark.lower == 980.
    assert mark.upper == 1020.
    assert validate_mark(mark)


def test_negative_measurement_uncertainty():
    with pytest.raises(ValueError):
        measurement_interval(
            value=1000.,
            expanded_uncertainty=-20.,
            source_id="synthetic-measurement",
            group="Sample A",
            units="g",
            method_id="synthetic-expanded-u"
        )

Run:

python -m pytest -v test_uncertainty_contract.py

The reference suite defines nineteen cases after expanding the nonfinite-source parameterization.

It checks numerical bounds, interval semantics, contributor integrity, missing units, invalid data, and measurement uncertainty.

These are code examples, not claims that the tests have been executed against a Sustainable Catalyst deployment.

13. Test rendering properties, not just image existence

A generated PNG or SVG file proves only that an artifact was written. It does not prove that its marks are numerically or scientifically correct.

Renderer tests should inspect:

  • Number of rendered estimates and intervals.
  • Estimate coordinates.
  • Lower and upper interval positions.
  • Correct mapping of uncertainty type to marks.
  • Axis units and labels.
  • Valid axis limits and interval visibility.
  • Group ordering.
  • Handling of asymmetric intervals.
  • Empty-state behavior.
  • Legend and caption accuracy.

13.1 Numeric-to-mark reconciliation

For a conventional error-bar mark:

plotted_estimate = estimate

plotted_lower = estimate - lower_error

plotted_upper = estimate + upper_error

Validate:

|plotted_lower - reference_lower|
    <= numerical_tolerance

|plotted_upper - reference_upper|
    <= numerical_tolerance

The tolerance must be justified by the calculation and renderer precision.

13.2 Independent visual inspection

Capture and inspect the actual exported figure.

Check that intervals are visible, not clipped, and identified accurately.

Where the renderer supports SVG or structured scene output, inspect its elements as additional evidence. Do not rely solely on a screenshot when machine-readable numerical properties are available.

14. Test empty data, missingness, and invalid numerical states

Production uncertainty-rendering code must define behavior for invalid or incomplete input.

Table 4. Negative-test scenarios
Scenario Expected response
Empty dataset Explicit no-data result; no fabricated interval
One observation for sample SD Reject or use a separately justified method
NaN input Apply documented missing-data policy or reject
Positive or negative infinity Reject invalid finite-statistic input
Lower bound above upper bound Reject invalid interval
Estimate outside conventional interval Reject under the declared central-estimate contract
Negative uncertainty magnitude Reject invalid uncertainty
Invalid coverage level Reject values outside (0,1)
Missing units Reject scientific publication output
Mixed unit dimensions Require validated conversion or separate axes
Duplicate source contributors Detect inconsistent lineage or justified replication semantics
Unsupported uncertainty type Reject rather than silently reinterpret
Clipped interval Detect and correct or explicitly disclose clipping

Missing values must not be silently converted to zero or interpolated as new measurements.

If exclusions are scientifically justified, preserve the exclusion rule and its effect on sample count and interval calculation.

15. Test unit conversions and extreme ranges

Uncertainty bounds must use the same compatible measurement units as their associated estimates.

For an affine conversion:

y = a*x + b

with exact a and b, standard uncertainty transforms as:

u_y = |a|*u_x

For example:

1000 ± 20 g

Equivalent:
1.000 ± 0.020 kg

Test unit prefixes, offsets, sign reversals, large and small magnitudes, and intervals that cross zero.

Also test the renderer’s numerical limits. An interval calculation may be valid in floating-point arithmetic while the graphical output overflows, clips, or loses useful precision.

For logarithmic axes, standard error bars that cross zero cannot be displayed faithfully on an ordinary positive logarithmic domain without additional handling.

16. Test temporal, spatial, and modeled uncertainty

16.1 Temporal uncertainty

For time-dependent intervals, validate:

  • Observation timestamps and time zones.
  • Alignment of estimates with interval bounds.
  • Time-dependent sample counts.
  • Missing periods.
  • Interpolation and resampling policies.
  • Pointwise versus simultaneous interval coverage.

A set of pointwise 95% confidence intervals does not automatically provide simultaneous 95% coverage across an entire time series.

16.2 Spatial uncertainty

Spatial uncertainty displays require appropriate handling of coordinate systems, spatial support, resolution, and spatial correlation.

Check that uncertainty maps distinguish modeled estimates from actual measurements and explicitly identify unobserved or masked regions.

16.3 Simulation ensembles

For simulation and scenario results, retain:

  • Model and parameter revisions.
  • Random seed and algorithm where applicable.
  • Simulation count and convergence information.
  • Ensemble weighting.
  • Statistical meaning of displayed quantiles or bands.
  • Calibration evidence where predictive coverage is claimed.

Do not label arbitrary scenario ranges as confidence or prediction intervals without a defensible statistical basis.

17. Performance and large-dataset acceptance

Uncertainty displays may involve thousands of groups, time points, ensemble members, or spatial cells.

Performance optimizations must not silently alter statistical meaning.

Test:

  • Numerical stability for large arrays.
  • Bounded memory consumption.
  • Rendering time and timeout behavior.
  • Downsampling rules.
  • Aggregation accuracy.
  • Interactive filter consistency.
  • Cache-key correctness.
  • Source revision changes.
  • Export fidelity.

If a visualization uses downsampling, record whether it changes only displayed marks or also affects the calculation of statistics.

A sampled display should not be described as showing every observation when records have been omitted.

18. Accessibility acceptance

Automated and manual testing should establish that the uncertainty figure remains interpretable without relying solely on color or visual inspection.

Check:

  • Keyboard-accessible controls.
  • Visible focus states.
  • Accessible labels and descriptions.
  • Non-color-only distinctions.
  • Appropriate contrast.
  • Readable interval markers.
  • Accessible numerical tables.
  • Correct interval terminology.
  • Meaningful empty and error states.

WCAG 2.2 and W3C guidance on complex images provide relevant accessibility requirements (W3C, 2024).

Automated checks should supplement manual evaluation with keyboard navigation and assistive technologies.

19. Security and export controls

Scientific figure exports can contain sensitive research information, including source identifiers, private dataset values, internal paths, and embedded metadata.

Test authorization for:

  • Source dataset access.
  • Derived uncertainty calculations.
  • Saved analytical states.
  • Rendering requests.
  • Export and download operations.
  • Publication approval.

For SVG and HTML output, review active content and untrusted text handling.

Do not assume that exported vector files are harmless merely because they represent charts. Unsafe content may be embedded or introduced through insufficient sanitization.

Production rendering services should enforce resource limits, content validation, appropriate file handling, and access policies.

20. Reproducibility and snapshot requirements

To reproduce an uncertainty figure, preserve:

  • Authoritative source identifier and immutable revision.
  • Contributing observation identifiers.
  • Source and output checksums.
  • Statistical method and assumptions.
  • Uncertainty type and interval level.
  • Numerical estimates and interval endpoints.
  • Measurement units and conversions.
  • Renderer engine and version.
  • Mark specifications and axis configuration.
  • Dependency environment.
  • Figure dimensions and output format.
  • Executed numerical and rendering tests.
  • Accessibility and scientific review evidence.

A reproducible numerical result may produce byte-different image files across renderer versions or operating systems.

Therefore, evaluate scientific numerical equivalence separately from exact file-hash identity.

20.1 Proposed evidence manifest

{
  "schema_version": "example-1.0",
  "figure_id": "synthetic-uncertainty-001",
  "source": {
    "artifact_id": "synthetic-fixture-v1",
    "revision": "1.0",
    "classification": "synthetic",
    "sha256": null
  },
  "analysis": {
    "method": "student_t",
    "interval_level": 0.95,
    "assumptions": [
      "independent_observations",
      "normal_population",
      "unknown_variance"
    ],
    "sample_size_per_group": 5
  },
  "uncertainty_types": [
    "confidence_interval",
    "prediction_interval"
  ],
  "rendering": {
    "engine": "matplotlib",
    "engine_version": null,
    "mark": "point_interval",
    "units": "synthetic_units"
  },
  "acceptance": {
    "schema_validation": "not_tested",
    "numerical_golden_tests": "not_tested",
    "interval_geometry": "not_tested",
    "visual_inspection": "not_tested",
    "accessibility": "not_tested",
    "security": "not_tested",
    "scientific_review": "not_tested"
  },
  "release_decision": "NO_GO"
}

This is an illustrative documentation contract, not a verified Sustainable Catalyst API or persisted database schema.

21. Scientific and technical acceptance matrix

Table 5. Uncertainty-renderer acceptance requirements
Criterion Pass condition Evidence
Source integrity Authoritative input and revision verified Source artifact and checksum
Schema validation Typed uncertainty fields conform to contract Positive and negative schema tests
Numerical correctness Results reproduce golden scientific fixtures Independent calculations
Uncertainty semantics Type, level, method, and assumptions explicit Method and metadata review
Contributors Source observation membership correct Record-level reconciliation
Interval geometry Rendered estimate and bounds match validated values Data-to-mark tests
Unit integrity Estimates and intervals use compatible units Dimensional checks
Missing-data handling Invalid and excluded observations treated transparently Boundary tests
Axis limits Relevant intervals are visible and accurately scaled Clipping and domain tests
Temporal/spatial alignment Estimates and intervals share correct coordinates Reference-system tests
Large-data behavior Performance controls preserve declared analytical meaning Load and regression tests
Accessibility Essential interval meaning available accessibly Manual and automated review
Security Data, rendering, and exports respect authorization Negative security tests
Snapshot reproducibility Accepted figures can be reconstructed from preserved inputs Independent replay receipt
Scientific interpretation Statistical claims justified by the method and data Independent scientific review
Publication approval Published output references an approved revision Release and review record

Decision rule: Record each applicable criterion as Pass, Fail, Not Tested, or Not Applicable. Mandatory failures or incomplete acceptance evidence prevent certification of the affected capability.

22. Sustainable Catalyst cross-application responsibilities

Uncertainty visualization is relevant to the intended integration of Sustainable Catalyst’s research, analytical, and publication systems.

The following responsibilities are proposed and must be verified against actual implementations.

Table 6. Proposed application responsibilities
Application Intended responsibility
Library Preserve source observations, uncertainty metadata, versions, permissions, and provenance
Workbench Calculate reproducible statistics, uncertainty estimates, and rendering inputs where implemented
Research Lab Assess statistical assumptions, measurement validity, and uncertainty propagation
Visualization & Graphing Render validated interval marks, distributions, bands, and accessible equivalents
Site Intelligence Represent geospatial uncertainty and spatial coverage where supported
Decision Studio Compare scenario uncertainty and modeled decision evidence where implemented
Workspace Manage analysis revisions, snapshots, validation evidence, and review controls
Research Publish scientifically approved uncertainty figures, methods, data, and citations

Proposed workflow:

Library source artifact
         |
         v
Workbench analytical result
         |
         v
Typed uncertainty contract
         |
         v
Visualization renderer
         |
         v
Numerical and graphical validation
         |
         v
Workspace scientific review
         |
         v
Approved Research publication

Each transition requires implementation-specific source, schema, authorization, and persistence verification.

23. Source audit and product certification

Before certifying uncertainty rendering in Sustainable Catalyst, attach:

  • Actual owning repository and code revision.
  • Implemented graphing engine and renderer adapter.
  • Actual uncertainty input and output schemas.
  • Statistical calculation code paths.
  • Source-to-mark provenance mapping.
  • Supported uncertainty methods and explicit limitations.
  • Unit conversion and missing-data behavior.
  • Renderer version and dependency environment.
  • Executed numerical golden-fixture tests.
  • Invalid-input and boundary tests.
  • Actual rendering screenshots and exported figures.
  • Accessibility and security test outcomes.
  • Persistence, snapshot replay, and publication-review evidence.
  • Known defects and unsupported configurations.

A library that supports plotting error bars does not necessarily implement validated uncertainty calculation, scientific provenance, or governed research publication.

24. Technical references

  1. Joint Committee for Guides in Metrology (JCGM) (2008). Evaluation of Measurement Data — Guide to the Expression of Uncertainty in Measurement. JCGM 100:2008. Available at: BIPM/JCGM publications.
  2. SciPy Community (n.d.). scipy.stats.t. Available at: SciPy documentation.
  3. Matplotlib Development Team (n.d.). matplotlib.pyplot.errorbar. Available at: Matplotlib documentation.
  4. Vega-Lite Developers (n.d.). Error Bar. Available at: Vega-Lite documentation.
  5. Vega-Lite Developers (n.d.). Error Band. Available at: Vega-Lite documentation.
  6. Harris, C.R. et al. (2020). ‘Array programming with NumPy’, Nature, 585, pp. 357–362. Available at: https://doi.org/10.1038/s41586-020-2649-2.
  7. pytest Development Team (n.d.). pytest Documentation. Available at: https://docs.pytest.org/en/stable/.
  8. World Wide Web Consortium (W3C) (2024). Web Content Accessibility Guidelines (WCAG) 2.2. Available at: https://www.w3.org/TR/WCAG22/.
  9. W3C Web Accessibility Initiative (n.d.). Complex Images. Available at: W3C WAI guidance.
  10. OWASP Foundation (n.d.). Cross Site Scripting Prevention Cheat Sheet. Available at: OWASP Cheat Sheet Series.

25. Completion and verification record

Table 7. Required development and testing record
Field Required evidence
Component identifier Renderer, adapter, or feature and revision
Source artifact Dataset identity, version, and checksum
Rendering contract Schema and supported uncertainty types
Statistical methods Algorithms, assumptions, and method revisions
Schema validation Pass, Fail, or Not Tested
Numerical correctness Pass, Fail, or Not Tested
Interval geometry Pass, Fail, or Not Tested
Source provenance Pass, Fail, or Not Tested
Unit consistency Pass, Fail, or Not Tested
Missing-data handling Pass, Fail, or Not Tested
Rendering and export Pass, Fail, or Not Tested
Performance Pass, Fail, or Not Tested
Accessibility Pass, Fail, or Not Tested
Security Pass, Fail, or Not Tested
Reproducibility Pass, Fail, or Not Tested
Scientific review Pass, Fail, or Not Tested
Publication approval Approved, Not Approved, or Not Applicable
Reviewer Actual reviewer and review date
Evidence artifacts Code, numerical fixtures, generated figures, logs, and test receipts
Outstanding limitations Unresolved scientific, security, or implementation concerns

Completion criterion: An uncertainty-rendering component is accepted when its typed input contract, numerical calculations, interval semantics, graphical mappings, units, provenance, accessibility, security, and reproducibility have satisfied applicable acceptance requirements. Scientific and publication approval remain separately documented decisions.

Scientific limitation: A correct rendering engine cannot validate an inappropriate statistical model, repair biased sampling, establish calibrated predictive coverage without evidence, or justify causal conclusions unsupported by the research design.

Current implementation status: Engineering methodology, typed uncertainty contract, synthetic reference implementation, golden numerical fixtures, negative tests, renderer example, and proposed scientific acceptance requirements documented. No specific Sustainable Catalyst renderer, statistical analysis service, or publication workflow is certified without implementation-specific source audit, executed tests, runtime inspection, and release acceptance evidence.

Scroll to Top