Skip to content

Bandwidth 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_kernel_weights

Show the spatial neighbourhood and weight-decay curve at one calibration point.

Property Value
Type function
Import from pygwrx.plotting import plot_kernel_weights
Signature plot_kernel_weights(model, focus: 'int' = 0, *, theme: 'str' = 'default', figsize: 'Optional[Tuple[float, float]]' = None, marker_size: 'float' = 55.0)
Maintained example examples/plotting/02_diagnostics_and_comparison.py

plot_kernel_weights

plot_kernel_weights(
    model,
    focus: int = 0,
    *,
    theme: str = "default",
    figsize: Optional[Tuple[float, float]] = None,
    marker_size: float = 55.0
)

Show the spatial neighbourhood and weight-decay curve at one calibration point.

Source code in src/pygwrx/plotting/bandwidth.py
def plot_kernel_weights(
    model,
    focus: int = 0,
    *,
    theme: str = "default",
    figsize: Optional[Tuple[float, float]] = None,
    marker_size: float = 55.0,
):
    """Show the spatial neighbourhood and weight-decay curve at one calibration point."""
    coords = model_coords(model)
    if not isinstance(focus, (int, np.integer)) or isinstance(focus, (bool, np.bool_)):
        raise TypeError("focus must be an integer calibration-row index.")
    index = int(focus)
    if index < 0 or index >= coords.shape[0]:
        raise IndexError(f"focus must lie in [0, {coords.shape[0] - 1}].")
    if not hasattr(model, "_weights_from_distances"):
        raise TypeError(
            "model does not expose the standard pyGWRx kernel-weight interface."
        )
    distances = compute_distance_matrix(
        coords[index : index + 1],
        coords,
        metric=getattr(model, "distance_metric", "euclidean"),
    ).reshape(-1)
    weights = np.asarray(model._weights_from_distances(distances), dtype=float).reshape(
        -1
    )

    with plotting_theme(theme):
        fig, axes = plt.subplots(1, 2, figsize=figsize or (10.0, 4.4))
        scatter = axes[0].scatter(
            coords[:, 0],
            coords[:, 1],
            c=weights,
            cmap="viridis",
            s=marker_size,
            edgecolors="0.2",
            linewidths=0.35,
        )
        axes[0].scatter(
            coords[index, 0],
            coords[index, 1],
            marker="*",
            s=marker_size * 3.0,
            color="none",
            edgecolors="black",
            linewidths=1.3,
            label=f"Focus {index}",
        )
        axes[0].set_aspect("equal", adjustable="datalim")
        axes[0].set_xlabel("X coordinate")
        axes[0].set_ylabel("Y coordinate")
        axes[0].set_title("Kernel neighbourhood")
        axes[0].legend(loc="best")
        fig.colorbar(scatter, ax=axes[0], fraction=0.046, pad=0.04, label="Weight")

        order = np.argsort(distances)
        axes[1].plot(distances[order], weights[order], marker="o", markersize=3)
        axes[1].set_xlabel("Distance from focus")
        axes[1].set_ylabel("Kernel weight")
        axes[1].set_title(
            f"{getattr(model, 'kernel', 'kernel')} decay; bandwidth={getattr(model, 'bandwidth_', np.nan)}"
        )
        axes[1].grid(True, alpha=0.25)
        fig.tight_layout()
        return fig, axes

plot_mgwr_bandwidths

Plot variable-specific MGWR bandwidths.

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

plot_mgwr_bandwidths

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

Plot variable-specific MGWR bandwidths.

Source code in src/pygwrx/plotting/bandwidth.py
def plot_mgwr_bandwidths(
    model,
    *,
    theme: str = "default",
    ax: Optional[plt.Axes] = None,
    figsize: Optional[Tuple[float, float]] = None,
    title: Optional[str] = None,
):
    """Plot variable-specific MGWR bandwidths."""
    bandwidths = getattr(model, "bandwidths_", None)
    if bandwidths is None:
        raise ValueError("The fitted model does not expose bandwidths_.")
    bandwidth_array = as_1d_finite(bandwidths, "bandwidths_")
    names = list(parameter_names(model, include_intercept=True))
    if len(names) != bandwidth_array.size:
        names = [f"parameter {index}" for index in range(bandwidth_array.size)]
    with plotting_theme(theme):
        if ax is None:
            fig, axis = plt.subplots(
                figsize=figsize or default_figure_size(theme, wide=True)
            )
        else:
            fig, axis = ax.figure, ax
        positions = np.arange(bandwidth_array.size)
        axis.barh(positions, bandwidth_array)
        axis.set_yticks(positions, labels=names)
        axis.invert_yaxis()
        axis.set_xlabel(
            "Adaptive neighbours"
            if getattr(model, "adaptive", False)
            else "Distance bandwidth"
        )
        axis.set_title(
            title or f"{model.__class__.__name__}: variable-specific bandwidths"
        )
        for position, value in zip(positions, bandwidth_array):
            text = (
                str(int(round(value)))
                if getattr(model, "adaptive", False)
                else f"{value:.4g}"
            )
            axis.text(value, position, f"  {text}", va="center")
        fig.tight_layout()
        return fig, axis

Runnable examples used on this page

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

"""All general residual, bandwidth, comparison, and collinearity 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 surface_models

from pygwrx.plotting import (
    compare_coefficient_surfaces,
    compare_model_diagnostics,
    plot_bandwidth_selection,
    plot_coefficient_variability,
    plot_diagnostic_panel,
    plot_kernel_weights,
    plot_local_collinearity,
    plot_local_diagnostics,
    plot_mgwr_bandwidths,
    plot_observed_vs_predicted,
    plot_qq,
    plot_residual_histogram,
    plot_residuals,
    plot_spatial_residuals,
)

X, y, coords, gwr, mgwr, lcr = surface_models()
plots = {
    "compare_surfaces.png": compare_coefficient_surfaces([gwr, mgwr], "x1"),
    "compare_diagnostics.png": compare_model_diagnostics([gwr, mgwr]),
    "kernel_weights.png": plot_kernel_weights(gwr, focus=3),
    "mgwr_bandwidths.png": plot_mgwr_bandwidths(mgwr),
    "residuals.png": plot_residuals(gwr.fitted_values_, gwr.residuals_),
    "residual_histogram.png": plot_residual_histogram(gwr.residuals_),
    "qq.png": plot_qq(gwr.residuals_),
    "spatial_residuals.png": plot_spatial_residuals(coords, gwr.residuals_),
    "observed_predicted.png": plot_observed_vs_predicted(y, gwr.fitted_values_),
    "bandwidth_selection.png": plot_bandwidth_selection(
        [10, 15, 20, 25], [14.0, 9.0, 7.5, 8.2], 20, criterion="AICc"
    ),
    "coefficient_variability.png": plot_coefficient_variability(
        gwr.coef_, feature_names=["x1", "x2"]
    ),
    "diagnostic_panel_arrays.png": plot_diagnostic_panel(
        y, gwr.fitted_values_, gwr.residuals_, coords
    ),
    "diagnostic_panel_model.png": plot_diagnostic_panel(gwr),
    "local_diagnostics.png": plot_local_diagnostics(
        coords, {"local_r2": gwr.local_r2_, "influence": gwr.influence_}
    ),
    "collinearity_gwr.png": plot_local_collinearity(gwr, "condition_number"),
    "collinearity_lcr.png": plot_local_collinearity(lcr, "local_lambda"),
}
for name, result in plots.items():
    print(save_plot(result, name))