Skip to content

CSpatial · spatial.variogram

Semivariogram (empirical, fitted model, permutation band)

Up to what distance do nearby measurements resemble each other, and how much variation is left over?

Half the average squared difference between pairs of sites, by distance. A fitted curve gives the nugget (variation at no distance), the sill (total variation) and the range (the distance past which sites stop resembling each other). A band from shuffled values shows what no spatial structure would look like.

Verified in Python and R Python and R agree to 6 decimals Seeded Also called variogram, semivariogram, semivariance…

A real result

Example “Meuse spherical”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

SemivariogramRecorded · Python and R agreeRecorded 2026-11-17 · 64 values compared · largest relative difference 1.3e-9
R

T = 0.391, p = .010, n = 155

T
0.3911
p
.010
Nugget
0.0616
Sill
0.6514
Practical range
942.52

Plots

Semivariogram of log_zincHow far does resemblance reach before sites are no more alike than any two sites?
View data
FittedSemivarianceDistanceShuffled highShuffled lowPairs
0.13370.130077.0190.71270.364752
0.20690.2091156.230.60750.4447263
0.29260.2952252.080.58680.4487381
0.37610.3835351.320.58020.4658430
0.45180.4412449.810.57430.4659475
0.51760.5212547.390.58070.4640503
0.57450.5520648.920.58370.4680525
0.61680.6154749.370.56580.4610565
0.64340.6770851.360.60180.4651535
0.65140.6440950.020.57100.4606530
0.65140.69051048.660.57920.4487487
0.65140.67101150.820.57760.4643483
0.65140.62561249.500.59140.4676431
0.65140.63421348.750.59230.4701419
0.65140.56451449.840.58540.4728427

Assumptions

  • Same mean and spread across the map — A trend makes the semivariogram keep rising past the data's variance. Remove it first and study the residuals.
  • Same pattern in every direction — The distance classes ignore direction; patterns along rivers or wind are not isotropic.
  • Enough pairs per distance — The smallest class has 52 pairs, enough to be stable.

Semivariance by distance class

Mean distancePairsSemivarianceShuffled lowShuffled highFitted
77.019520.13000.36470.71270.1337
156.232630.20910.44470.60750.2069
252.083810.29520.44870.58680.2926
351.324300.38350.46580.58020.3761
449.814750.44120.46590.57430.4518
547.395030.52120.46400.58070.5176
648.925250.55200.46800.58370.5745
749.375650.61540.46100.56580.6168
851.365350.67700.46510.60180.6434
950.025300.64400.46060.57100.6514
1048.664870.69050.44870.57920.6514
1150.824830.67100.46430.57760.6514
1249.504310.62560.46760.59140.6514
1348.754190.63420.47010.59230.6514
1449.844270.56450.47280.58540.6514
  • 15 classes up to distance 1500; T is the largest gap between semivariance and the data's variance, tested on 99 shuffles of the values (seed 42).
Python

T = 0.391, p = .010, n = 155

T
0.3911
p
.010
Nugget
0.0616
Sill
0.6514
Practical range
942.52

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Same mean and spread across the map — A trend makes the semivariogram keep rising past the data's variance. Remove it first and study the residuals.
  • Same pattern in every direction — The distance classes ignore direction; patterns along rivers or wind are not isotropic.
  • Enough pairs per distance — The smallest class has 52 pairs, enough to be stable.

Semivariance by distance class

Mean distancePairsSemivarianceShuffled lowShuffled highFitted
77.019520.13000.36470.71270.1337
156.232630.20910.44470.60750.2069
252.083810.29520.44870.58680.2926
351.324300.38350.46580.58020.3761
449.814750.44120.46590.57430.4518
547.395030.52120.46400.58070.5176
648.925250.55200.46800.58370.5745
749.375650.61540.46100.56580.6168
851.365350.67700.46510.60180.6434
950.025300.64400.46060.57100.6514
1048.664870.69050.44870.57920.6514
1150.824830.67100.46430.57760.6514
1249.504310.62560.46760.59140.6514
1348.754190.63420.47010.59230.6514
1449.844270.56450.47280.58540.6514
  • 15 classes up to distance 1500; T is the largest gap between semivariance and the data's variance, tested on 99 shuffles of the values (seed 42).

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Meuse sphericalsp_meuse · x_coord: x · y: log_zinc · y_coord: y
  • Meuse exponentialsp_meuse · x_coord: x · y: log_zinc · y_coord: y
  • Meuse gaussian robustsp_meuse · x_coord: x · y: zinc · y_coord: y
  • Nc lonlat no modelsp_nc_sids · x_coord: lon · y: rate · y_coord: lat
  • Degenerate n3sp_meuse · x_coord: x · y: log_zinc · y_coord: y

In the guides

Where it sits in the decision guides

  • Continuous–continuous: Pearson / Spearman / Kendall · Statistics Guide · C — Test association

What you need

Variablenumeric · 1 column
What you measured at each site, for example a soil concentration.
X or longitudenumeric · 1 column
Each site's horizontal position, in map units or degrees east.
Y or latitudenumeric · 1 column
Each site's vertical position, in map units or degrees north.

Choices you make

options

Coordinatesdefault planar

What the coordinates are.

  • Planar (meters, kilometers, grid units)(default) — Distances are straight lines in the coordinates' own units.
  • Longitude and latitude (degrees) — Projected to kilometers at the sites' mean latitude; suits a region, not a continent.
Estimatordefault matheron

How semivariance is estimated in each distance class.

  • Matheron (classical)(default) — Half the mean squared difference: the standard estimator, sensitive to outliers.
  • Cressie–Hawkins (robust) — Based on square roots of absolute differences; less affected by outliers.
Fitted modeldefault spherical

The curve fitted by weighted least squares, weighting by pairs over squared distance.

  • Spherical(default) — Rises almost in a straight line and levels off at a definite range.
  • Exponential — Levels off gradually; the practical range is three times the parameter.
  • Gaussian — Flat near zero, for very smooth surfaces; the practical range is √3 times the parameter.
  • No model — Only the empirical semivariogram and its band.
Largest distancedefault —

Pairs further apart than this are ignored; long distances have few pairs near the map's edges.

Distance classesdefault 15

Equal-width classes up to the largest distance; aim for at least 30 pairs in each.

hypothesis

Permutationsdefault 199

Shuffles of the values for the band and the test of any spatial structure.

Significance leveldefault 0.05

Level used in the narrative.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Same mean and spread across the map

    A trend makes the semivariogram keep rising; remove it first and study the residuals.

  • Same pattern in every direction

    The distance classes ignore direction; patterns along rivers or wind are not isotropic.

  • Enough pairs per distance

    Classes with fewer than 30 pairs are noisy.

What it reports

  • Tests: No spatial structure in the values
n
How many independent units the analysis used; it sets precision and power.
variance
The average squared distance from the mean; the SD squared.
cutoff
Half the average squared difference between pairs of sites, by distance. Low at short range when nearby sites resemble each other.
width
Half the average squared difference between pairs of sites, by distance. Low at short range when nearby sites resemble each other.
n_lags
How many independent units the analysis used; it sets precision and power.
min_pairs
Half the average squared difference between pairs of sites, by distance. Low at short range when nearby sites resemble each other.
nugget
The semivariance at distance zero, from measurement error and variation closer than your closest pair of sites.
psill
The level where a semivariogram flattens out, close to the data's total variance.
sill
The level where a semivariogram flattens out, close to the data's total variance.
range
The distance past which sites stop resembling each other. Samples further apart than this carry nearly independent information.
effective_range
The distance past which sites stop resembling each other. Samples further apart than this carry nearly independent information.
nugget_share
The semivariance at distance zero, from measurement error and variation closer than your closest pair of sites.
sse
Half the average squared difference between pairs of sites, by distance. Low at short range when nearby sites resemble each other.
T
How many other points lie within distance r of a typical point, against what random points would give. L(r) = r under randomness.
p
How surprising your data would be if the null hypothesis were true, as a probability.
gamma_first
Half the average squared difference between pairs of sites, by distance. Low at short range when nearby sites resemble each other.
gamma_last
Half the average squared difference between pairs of sites, by distance. Low at short range when nearby sites resemble each other.
n_perm
How many independent units the analysis used; it sets precision and power.
missing_share
Values that were not recorded; how they went missing decides which fixes are safe.

Per group, level or term: gamma[<class>], pairs[<class>], h[<class>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Empirical semivariances and pair counts match gstat::variogram exactly. The fit is a twin (range profiled, then golden-section search), agreeing with gstat::fit.variogram (weights N/h²) to about 1e-4 relative on Meuse log zinc: the optimizers differ, not the objective.
  • gstat's robust estimator leaves out the 0.045/N² term of Cressie & Hawkins (1980); the twin includes it, a difference below 1e-6 for classes with hundreds of pairs.
Python

The exact script CodeSplash ran for example “Meuse spherical” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Semivariogram (empirical, fitted model, permutation band)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.variogram 1.0.1 · spec 59aa50ddc1214876
# Dataset: sp_meuse (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.stats import spatial_points as spp

# %% Data
df = pd.read_parquet("tests/parity/fixtures/sp_meuse.parquet", columns=["log_zinc", "x", "y"])
n_input = len(df)
df = df.dropna(subset=["log_zinc", "x", "y"])  # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["log_zinc", "x", "y"])  # infinite values stop the run (registry/errors.yaml)

# %% Test
# Semivariance by distance class (Matheron 1962; Cressie & Hawkins 1980), a model fitted by weighted least squares
# with weights N/h² (Cressie 1985), and a band from shuffled values on the shared random stream.
Y = "log_zinc"
coordinates = "planar"  # planar | lonlat
estimator = "matheron"  # matheron | cressie
model = "spherical"  # spherical | exponential | gaussian | none
cutoff = 1500
n_lags = int(15)
n_perm = int(99)
alpha = 0.05
seed = 42
px, py = spp.project(df["x"].to_numpy(dtype=float), df["y"].to_numpy(dtype=float), coordinates)
z = df[Y].to_numpy(dtype=float)
n = z.size
res = spp.variogram(px, py, z, cutoff, n_lags, estimator, model, n_perm, seed)
h, gamma, pairs, fit, p = res["h"], res["gamma"], res["pairs"], res["fit"], res["p"]

# %% Assumptions
min_pairs = int(np.min(pairs))
assumptions = [
    {"key": "stationary", "label": "Same mean and spread across the map", "status": "info",
     "detail": "A trend makes the semivariogram keep rising past the data's variance. Remove it first and study the residuals."},
    {"key": "isotropic", "label": "Same pattern in every direction", "status": "info",
     "detail": "The distance classes ignore direction; patterns along rivers or wind are not isotropic."},
    {"key": "pairs", "label": "Enough pairs per distance", "status": "pass" if min_pairs >= 30 else "warn",
     "detail": f"The smallest class has {min_pairs} pairs" + (", enough to be stable." if min_pairs >= 30 else "; classes under 30 pairs are noisy. Use fewer classes or a larger distance.")},
]

# %% Result
values = {"n": n, "variance": res["variance"], "cutoff": res["cutoff"], "width": res["width"], "n_lags": res["n_lags"], "min_pairs": min_pairs,
          "T": res["T"], "p": p, "gamma_first": float(gamma[0]), "gamma_last": float(gamma[-1]), "n_perm": n_perm,
          "missing_share": n_dropped / n_input if n_input else 0.0}
for k in range(h.size):
    values[f"gamma[{k + 1}]"] = float(gamma[k])
    values[f"pairs[{k + 1}]"] = float(pairs[k])
    values[f"h[{k + 1}]"] = float(h[k])
if fit:
    values.update({key: fit[key] for key in ("nugget", "psill", "sill", "range", "effective_range", "nugget_share", "sse")})
verdict = "Nearby sites resemble each other more than shuffled values would." if p < alpha else "The data are compatible with no spatial structure at these distances."
fit_text = (f" A {model} model gives nugget {fit['nugget']:.3g}, sill {fit['sill']:.3g} and practical range {fit['effective_range']:.3g}." if fit else "")
summary = f"Semivariogram of {Y} ({n} sites): {cs.fmt_p(p)} against shuffled values. {verdict}{fit_text}"
columns = [{"key": "h", "label": "Mean distance", "type": "number"}, {"key": "pairs", "label": "Pairs", "type": "integer"}, {"key": "gamma", "label": "Semivariance", "type": "number"},
           {"key": "lo", "label": "Shuffled low", "type": "number"}, {"key": "hi", "label": "Shuffled high", "type": "number"}]
rows = [{"h": float(h[k]), "pairs": float(pairs[k]), "gamma": float(gamma[k]), "lo": float(res["lo"][k]), "hi": float(res["hi"][k])} for k in range(h.size)]
if fit:
    columns.append({"key": "fitted", "label": "Fitted", "type": "number"})
    for k in range(h.size):
        rows[k]["fitted"] = float(res["fitted"][k])
tables = [{"key": "classes", "title": "Semivariance by distance class", "columns": columns, "rows": rows}]
roles = {"h": cs.col("Distance", h), "gamma": cs.col("Semivariance", gamma), "pairs": cs.col("Pairs", pairs),
         "lo": cs.col("Shuffled low", res["lo"]), "hi": cs.col("Shuffled high", res["hi"])}
if fit:
    roles["fitted"] = cs.col("Fitted", res["fitted"])
charts = [cs.chart("variogram", "variogram", f"Semivariogram of {Y}", roles, controls={"variance": res["variance"]})]
statistics = [{"key": "T", "label": "T", "value": res["T"]}, {"key": "p", "label": "p", "value": p, "format": "p"}]
if fit:
    statistics += [{"key": "nugget", "label": "Nugget", "value": fit["nugget"]}, {"key": "sill", "label": "Sill", "value": fit["sill"]},
                   {"key": "effective_range", "label": "Practical range", "value": fit["effective_range"]}]
for key in ["nugget", "psill", "sill", "range", "effective_range", "nugget_share", "sse"]:  # only some options produce these
    values.setdefault(key, None)
cs.publish({
    "method": "spatial.variogram",
    "methodVersion": "1.0.1",
    "title": "Semivariogram",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"T = {res['T']:.3g}, {cs.fmt_p(p)}, n = {n}",
    "statistics": statistics,
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"{res['n_lags']} classes up to distance {res['cutoff']:.4g}; T is the largest gap between semivariance and the data's variance, tested on {n_perm} shuffles of the values (seed {seed})."],
    "values": values,
    "charts": charts,
})
R

The exact script CodeSplash ran for example “Meuse spherical” · R version 4.5.1 (2025-06-13)

# Semivariogram (empirical, fitted model, permutation band)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.variogram 1.0.1 · spec 59aa50ddc1214876
# Dataset: sp_meuse (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/sp_meuse.parquet", col_select = c("log_zinc", "x", "y")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("log_zinc", "x", "y")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("log_zinc", "x", "y"))  # infinite values stop the run (registry/errors.yaml)

# %% Test
# Semivariance by distance class (Matheron 1962; Cressie & Hawkins 1980), a model fitted by weighted least squares
# with weights N/h² (Cressie 1985), and a band from shuffled values on the shared random stream.
Y <- "log_zinc"
coordinates <- "planar"  # planar | lonlat
estimator <- "matheron"  # matheron | cressie
model <- "spherical"  # spherical | exponential | gaussian | none
cutoff <- 1500
n_lags <- as.integer(15)
n_perm <- as.integer(99)
alpha <- 0.05
seed <- 42
pr <- cs_spp_project(df[["x"]], df[["y"]], coordinates)
z <- as.numeric(df[[Y]])
n <- length(z)
res <- cs_spp_variogram(pr$x, pr$y, z, cutoff, n_lags, estimator, model, n_perm, seed)
h <- res$h
gamma <- res$gamma
pairs <- res$pairs
fit <- res$fit
p <- res$p

# %% Assumptions
min_pairs <- as.integer(min(pairs))
assumptions <- list(
  list(key = "stationary", label = "Same mean and spread across the map", status = "info",
       detail = "A trend makes the semivariogram keep rising past the data's variance. Remove it first and study the residuals."),
  list(key = "isotropic", label = "Same pattern in every direction", status = "info",
       detail = "The distance classes ignore direction; patterns along rivers or wind are not isotropic."),
  list(key = "pairs", label = "Enough pairs per distance", status = if (min_pairs >= 30) "pass" else "warn",
       detail = paste0(sprintf("The smallest class has %d pairs", min_pairs), if (min_pairs >= 30) ", enough to be stable." else "; classes under 30 pairs are noisy. Use fewer classes or a larger distance."))
)

# %% Result
values <- list(n = n, variance = res$variance, cutoff = res$cutoff, width = res$width, n_lags = res$n_lags, min_pairs = min_pairs,
               T = res$T, p = p, gamma_first = gamma[1], gamma_last = gamma[length(gamma)], n_perm = n_perm,
               missing_share = if (n_input > 0) n_dropped / n_input else 0)
for (k in seq_along(h)) {
  values[[sprintf("gamma[%d]", k)]] <- gamma[k]
  values[[sprintf("pairs[%d]", k)]] <- pairs[k]
  values[[sprintf("h[%d]", k)]] <- h[k]
}
if (!is.null(fit)) values <- c(values, fit[c("nugget", "psill", "sill", "range", "effective_range", "nugget_share", "sse")])
verdict <- if (p < alpha) "Nearby sites resemble each other more than shuffled values would." else "The data are compatible with no spatial structure at these distances."
fit_text <- if (!is.null(fit)) sprintf(" A %s model gives nugget %.3g, sill %.3g and practical range %.3g.", model, fit$nugget, fit$sill, fit$effective_range) else ""
summary <- sprintf("Semivariogram of %s (%d sites): %s against shuffled values. %s%s", Y, n, cs_fmt_p(p), verdict, fit_text)
columns <- list(list(key = "h", label = "Mean distance", type = "number"), list(key = "pairs", label = "Pairs", type = "integer"), list(key = "gamma", label = "Semivariance", type = "number"),
                list(key = "lo", label = "Shuffled low", type = "number"), list(key = "hi", label = "Shuffled high", type = "number"))
rows <- lapply(seq_along(h), function(k) list(h = h[k], pairs = pairs[k], gamma = gamma[k], lo = res$lo[k], hi = res$hi[k]))
if (!is.null(fit)) {
  columns[[length(columns) + 1L]] <- list(key = "fitted", label = "Fitted", type = "number")
  for (k in seq_along(h)) rows[[k]]$fitted <- res$fitted[k]
}
tables <- list(list(key = "classes", title = "Semivariance by distance class", columns = columns, rows = rows))
chart_roles <- list(h = cs_col("Distance", h), gamma = cs_col("Semivariance", gamma), pairs = cs_col("Pairs", pairs),
                    lo = cs_col("Shuffled low", res$lo), hi = cs_col("Shuffled high", res$hi))
if (!is.null(fit)) chart_roles$fitted <- cs_col("Fitted", res$fitted)
charts <- list(cs_chart("variogram", "variogram", sprintf("Semivariogram of %s", Y), chart_roles, controls = list(variance = res$variance)))
statistics <- list(list(key = "T", label = "T", value = res$T), list(key = "p", label = "p", value = p, format = "p"))
if (!is.null(fit)) {
  statistics <- c(statistics, list(list(key = "nugget", label = "Nugget", value = fit$nugget), list(key = "sill", label = "Sill", value = fit$sill),
                                   list(key = "effective_range", label = "Practical range", value = fit$effective_range)))
}
for (key in c("nugget", "psill", "sill", "range", "effective_range", "nugget_share", "sse")) if (is.null(values[[key]])) values[[key]] <- NA_real_  # only some options produce these
cs_publish(list(
  method = "spatial.variogram",
  methodVersion = "1.0.1",
  title = "Semivariogram",
  engine = cs_engine_info("stats"),
  n = n,
  summary = summary,
  apa = sprintf("T = %.3g, %s, n = %d", res$T, cs_fmt_p(p), n),
  statistics = statistics,
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("%d classes up to distance %.4g; T is the largest gap between semivariance and the data's variance, tested on %d shuffles of the values (seed %d).", res$n_lags, res$cutoff, n_perm, seed)),
  values = values,
  charts = charts
))

Sources

  • Matheron, G. (1962). Traité de géostatistique appliquée. Technip.
  • Cressie, N., & Hawkins, D. M. (1980). Robust estimation of the variogram. Mathematical Geology, 12, 115–125.
  • Cressie, N. (1985). Fitting variogram models by weighted least squares. Mathematical Geology, 17, 563–586.

From the CodeSplash method registry · spatial.variogram v1.0.1.