Skip to content

Bootstrap plots

This page documents 2 public symbols. Each entry includes its purpose, import path, full API docstring, and the maintained example that exercises it.

Conceptual guide

plot_bootstrap_pvalues

Map localized bootstrap p values or show a global modified-test p value.

Property Value
Type function
Import from pygwrx.plotting import plot_bootstrap_pvalues
Signature plot_bootstrap_pvalues(model, feature, *, test: 'str' = 'localized', geometry=None, alpha: 'float' = 0.05, theme: 'str' = 'default', ax: 'Optional[plt.Axes]' = None, figsize: 'Optional[Tuple[float, float]]' = None, title: 'Optional[str]' = None)
Maintained example examples/plotting/03_robust_regularized_bootstrap.py

plot_bootstrap_pvalues

plot_bootstrap_pvalues(
    model,
    feature,
    *,
    test: str = "localized",
    geometry=None,
    alpha: float = 0.05,
    theme: str = "default",
    ax: Optional[Axes] = None,
    figsize: Optional[Tuple[float, float]] = None,
    title: Optional[str] = None
)

Map localized bootstrap p values or show a global modified-test p value.

Source code in src/pygwrx/plotting/bootstrap.py
def plot_bootstrap_pvalues(
    model,
    feature,
    *,
    test: str = "localized",
    geometry=None,
    alpha: float = 0.05,
    theme: str = "default",
    ax: Optional[plt.Axes] = None,
    figsize: Optional[Tuple[float, float]] = None,
    title: Optional[str] = None,
):
    """Map localized bootstrap p values or show a global modified-test p value."""
    index, label = _parameter_index(model, feature)
    token = str(test).strip().lower()
    if token == "localized":
        values = np.asarray(getattr(model, "localized_p_values_", None), dtype=float)
        if values.ndim != 2:
            raise ValueError("The fitted model does not expose localized_p_values_.")
        p = values[:, index]
    elif token == "modified":
        values = np.asarray(
            getattr(model, "modified_p_values_", None), dtype=float
        ).reshape(-1)
        if index >= values.size:
            raise ValueError(
                "modified_p_values_ does not contain the requested parameter."
            )
        p = np.full(coords_for_model(model).shape[0], values[index])
    else:
        raise ValueError("test must be 'localized' or 'modified'.")
    with plotting_theme(theme):
        fig, axis = figure_axis(ax, figsize, theme)
        cmap, norm = resolve_color_scale(
            p, center_zero=False, vmin=0.0, vmax=1.0, cmap="viridis_r"
        )
        artist = render_spatial_values(
            axis,
            p,
            coords=coords_for_model(model),
            geometry=geometry,
            cmap=cmap,
            norm=norm,
        )
        add_colorbar(fig, axis, artist, "Bootstrap p value")
        significant = int(np.sum(p <= alpha))
        axis.text(
            0.02,
            0.02,
            f"p ≤ {alpha:g}: {significant}/{p.size}",
            transform=axis.transAxes,
            bbox={"facecolor": "white", "edgecolor": "0.5", "alpha": 0.85},
        )
        axis.set_title(title or f"Bootstrap {token} test: {label}")
        fig.tight_layout()
        return fig, axis

plot_bootstrap_bandwidths

Plot bandwidth variability across bootstrap replications.

Property Value
Type function
Import from pygwrx.plotting import plot_bootstrap_bandwidths
Signature plot_bootstrap_bandwidths(model, *, theme: 'str' = 'default', ax: 'Optional[plt.Axes]' = None, figsize: 'Optional[Tuple[float, float]]' = None, title: 'str' = 'Bootstrap bandwidth distribution')
Maintained example examples/plotting/03_robust_regularized_bootstrap.py

plot_bootstrap_bandwidths

plot_bootstrap_bandwidths(
    model,
    *,
    theme: str = "default",
    ax: Optional[Axes] = None,
    figsize: Optional[Tuple[float, float]] = None,
    title: str = "Bootstrap bandwidth distribution"
)

Plot bandwidth variability across bootstrap replications.

Source code in src/pygwrx/plotting/bootstrap.py
def plot_bootstrap_bandwidths(
    model,
    *,
    theme: str = "default",
    ax: Optional[plt.Axes] = None,
    figsize: Optional[Tuple[float, float]] = None,
    title: str = "Bootstrap bandwidth distribution",
):
    """Plot bandwidth variability across bootstrap replications."""
    values = np.asarray(
        getattr(model, "bootstrap_bandwidths_", None), dtype=float
    ).reshape(-1)
    if values.size == 0 or not np.all(np.isfinite(values)):
        raise ValueError(
            "The fitted model does not expose finite bootstrap_bandwidths_."
        )
    with plotting_theme(theme):
        fig, axis = figure_axis(ax, figsize, theme)
        axis.hist(values, bins="auto", edgecolor="0.25", linewidth=0.5)
        observed = getattr(model, "bandwidth_", None)
        if observed is not None:
            axis.axvline(float(observed), color="0.2", linestyle="--", label="Observed")
            axis.legend(loc="best")
        axis.set_xlabel("Bandwidth")
        axis.set_ylabel("Bootstrap count")
        axis.set_title(title)
        axis.grid(True, axis="y", alpha=0.22)
        fig.tight_layout()
        return fig, axis

Runnable examples used on this page

examples/plotting/03_robust_regularized_bootstrap.py
# SPDX-FileCopyrightText: 2026 Jinghao Hu
# SPDX-License-Identifier: MIT

"""All robust, GLM, Lasso, mixed, bootstrap, and scalable plots."""

# Allow this script to run directly from any working directory.
import sys
from pathlib import Path

_PROJECT_ROOT = Path(__file__).resolve().parents[2]
_EXAMPLES_ROOT = _PROJECT_ROOT / "examples"
_SRC_ROOT = _PROJECT_ROOT / "src"
for _path in (_SRC_ROOT, _EXAMPLES_ROOT):
    if str(_path) not in sys.path:
        sys.path.insert(0, str(_path))

import matplotlib

matplotlib.use("Agg", force=True)
from _common import save_plot
from _models import regularized_models

from pygwrx.plotting import (
    plot_bootstrap_bandwidths,
    plot_bootstrap_pvalues,
    plot_gwglm_residuals,
    plot_gwlasso_active_map,
    plot_gwlasso_alpha,
    plot_gwlasso_selection_frequency,
    plot_mixed_gwr_coefficients,
    plot_rgwr_convergence,
    plot_rgwr_weights,
    plot_scalable_gwr_kernel,
)

X, y, coords, rgwr, gwglm, gwlasso, mixed, bootstrap, scalable = regularized_models()
plots = {
    "rgwr_weights.png": plot_rgwr_weights(rgwr),
    "rgwr_convergence.png": plot_rgwr_convergence(rgwr),
    "gwglm_residuals.png": plot_gwglm_residuals(gwglm),
    "gwlasso_frequency.png": plot_gwlasso_selection_frequency(gwlasso),
    "gwlasso_active.png": plot_gwlasso_active_map(gwlasso, "x1"),
    "gwlasso_alpha.png": plot_gwlasso_alpha(gwlasso),
    "mixed_coefficients.png": plot_mixed_gwr_coefficients(mixed),
    "bootstrap_pvalues.png": plot_bootstrap_pvalues(bootstrap, "x1"),
    "bootstrap_bandwidths.png": plot_bootstrap_bandwidths(bootstrap),
    "scalable_kernel.png": plot_scalable_gwr_kernel(scalable),
}
for name, result in plots.items():
    print(save_plot(result, name))