Skip to content

CSpatial · spatial.quadrat

Quadrat counts (test of complete spatial randomness)

Do points fall evenly across equal parts of the map?

Divides the window into a grid of equal cells and compares the counts with what random points would give, using a chi-square test or simulated patterns. The result depends on the grid, so choose it before you look at the data.

Verified in Python and R Python and R agree to 10 decimals Seeded Also called quadrat count, quadrat test, quadrat.test…

A real result

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

Quadrat countsRecorded · Python and R agreeRecorded 2026-11-17 · 12 values compared
R

χ²(8) = 4.29, p = .170

X²
4.286
df
8
p
.170
Variance-to-mean ratio
0.5357

Plots

Points per cell (4.7 expected)What do the values of a square or rectangular result matrix look like at a glance?
View data
ColumnRowCount
Column 1Row 13
Column 2Row 16
Column 3Row 14
Column 1Row 24
Column 2Row 27
Column 3Row 26
Column 1Row 33
Column 2Row 36
Column 3Row 33

Assumptions

  • Grid chosen in advance — A 3 × 3 grid. Different grids give different p-values; trying several and keeping one inflates false alarms.
  • Enough points per cell — 4.7 points expected per cell: too few for the chi-square reference. Use simulated patterns or a coarser grid.
  • Constant intensity — Density that varies across the window looks like clustering; this test cannot tell the two apart.

Counts by cell (row 1 at the bottom)

RowColumnCount
Row 1Column 13
Row 1Column 26
Row 1Column 34
Row 2Column 14
Row 2Column 27
Row 2Column 36
Row 3Column 13
Row 3Column 26
Row 3Column 33
  • Chi-square reference. A variance-to-mean ratio above 1 points to clustering, below 1 to regularity.
Python

χ²(8) = 4.29, p = .170

X²
4.286
df
8
p
.170
Variance-to-mean ratio
0.5357

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

Assumptions

  • Grid chosen in advance — A 3 × 3 grid. Different grids give different p-values; trying several and keeping one inflates false alarms.
  • Enough points per cell — 4.7 points expected per cell: too few for the chi-square reference. Use simulated patterns or a coarser grid.
  • Constant intensity — Density that varies across the window looks like clustering; this test cannot tell the two apart.

Counts by cell (row 1 at the bottom)

RowColumnCount
Row 1Column 13
Row 1Column 26
Row 1Column 34
Row 2Column 14
Row 2Column 27
Row 2Column 36
Row 3Column 13
Row 3Column 26
Row 3Column 33
  • Chi-square reference. A variance-to-mean ratio above 1 points to clustering, below 1 to regularity.

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

  • Guide pointssp_guide_points · x_coord: x · y_coord: y
  • Cells regularsp_cells · x_coord: x · y_coord: y
  • Redwood clustered simulatedsp_redwood · x_coord: x · y_coord: y
  • Pines bboxsp_japanesepines · x_coord: x · y_coord: y
  • Degenerate tiessp_guide_points · x_coord: x · 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

X or longitudenumeric · 1 column
Each point's horizontal position, in map units or degrees east.
Y or latitudenumeric · 1 column
Each point'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) — Equal cells in the coordinates' own units.
  • Longitude and latitude (degrees) — Projected to kilometers at the points' mean latitude; suits a region, not a continent.
Observation windowdefault bbox

The area in which points could have been found.

  • Bounding box of the points(default) — The smallest rectangle around the points.
  • Stated rectangle — The area actually searched, including where no points were found.
Window x minimumdefault —

Left edge of the searched rectangle, in the coordinates' units.

Window x maximumdefault —

Right edge of the searched rectangle, in the coordinates' units.

Window y minimumdefault —

Bottom edge of the searched rectangle, in the coordinates' units.

Window y maximumdefault —

Top edge of the searched rectangle, in the coordinates' units.

Columnsdefault 5

Cells across. Aim for an expected count of at least 5 in each cell.

Rowsdefault 5

Cells up. Aim for an expected count of at least 5 in each cell.

hypothesis

Alternativedefault two_sided

The pattern you expect, stated before testing.

  • Either direction(default) — Clustered or regular.
  • Clustered — Counts more variable than random: some cells crowded, some empty.
  • Regular — Counts more even than random.
Reference distributiondefault chisq

How the p-value is calibrated.

  • Chi-square(default) — Good when every cell expects at least 5 points.
  • Simulated random patterns — Uniform points with the same count; use it when expected counts are small.
Simulated patternsdefault 999

Random patterns for the simulated p; the smallest possible p is 1/(B + 1).

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.

  • Grid chosen in advance

    Different grids give different p-values; trying several and keeping one inflates false alarms.

  • Enough points per cell

    The chi-square reference needs about 5 expected points per cell; otherwise simulate.

  • Constant intensity

    Density that varies across the window looks like clustering.

What it reports

  • Tests: The points follow complete spatial randomness
X2
A sum of squared, scaled differences between observed and expected counts or estimates.
df
How much independent information is left to estimate variability after fitting the model.
p
How surprising your data would be if the null hypothesis were true, as a probability.
p_analytic
What the statistic would look like with values placed at random across sites, by shuffling them or from a normal approximation.
n
How many independent units the analysis used; it sets precision and power.
n_quadrats
Counts in a grid of equal cells, compared with what random points would give.
expected
What the statistic would look like with values placed at random across sites, by shuffling them or from a normal approximation.
vmr
The variance of the counts over their mean; about 1 for random points, above 1 clustered, below 1 regular.
min_count
Counts in a grid of equal cells, compared with what random points would give.
max_count
Counts in a grid of equal cells, compared with what random points would give.
n_sim
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.

Python and R

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

Default traps between the two languages

  • Simulated patterns come from the shared Wichmann–Hill stream. X² and its chi-square p match spatstat.explore::quadrat.test to 1e-9; its two-sided p is also twice the smaller tail.
Python

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

# Quadrat counts (test of complete spatial randomness)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.quadrat 1.0.1 · spec 8347412c7cb179d4
# Dataset: sp_cells (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_cells.parquet", columns=["x", "y"])
n_input = len(df)
df = df.dropna(subset=["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, ["x", "y"])  # infinite values stop the run (registry/errors.yaml)

# %% Test
# Counts in a grid of equal cells against equal expected counts: Pearson's X² (Greig-Smith 1952), or a null of
# uniform patterns from the shared random stream.
X = "x"
Y = "y"
coordinates = "planar"  # planar | lonlat
nx = int(3)
ny = int(3)
alternative = "regular"  # two_sided | clustered | regular
calibration = "chisq"  # chisq | simulation
n_sim = int(999)
alpha = 0.05
seed = 42
px, py = spp.project(df[X].to_numpy(dtype=float), df[Y].to_numpy(dtype=float), coordinates)
n = px.size
wx0, wy0 = spp.project(np.array([0, 1]), np.array([0, 1]), coordinates)
w = spp.window(px, py, "custom", wx0[0], wx0[1], wy0[0], wy0[1], names=(X, Y))
res = spp.quadrat_test(px, py, w, nx, ny, alternative, calibration, n_sim, seed)
x2, df_chi, p, vmr, expected = res["X2"], res["df"], res["p"], res["vmr"], res["expected"]
counts = res["counts"]

# %% Assumptions
small = expected < 5 and calibration == "chisq"
assumptions = [
    {"key": "grid_fixed", "label": "Grid chosen in advance", "status": "info", "detail": f"A {nx} × {ny} grid. Different grids give different p-values; trying several and keeping one inflates false alarms."},
    {"key": "expected_counts", "label": "Enough points per cell", "status": "warn" if small else "pass",
     "detail": f"{expected:.1f} points expected per cell" + (": too few for the chi-square reference. Use simulated patterns or a coarser grid." if small else ".")},
    {"key": "homogeneous", "label": "Constant intensity", "status": "info", "detail": "Density that varies across the window looks like clustering; this test cannot tell the two apart."},
]

# %% Result
if p < alpha:
    verdict = "Counts vary more than random points would: a clustered pattern." if vmr > 1 else "Counts are more even than random points would be: a regular pattern."
else:
    verdict = "The points are compatible with complete spatial randomness at this grid size."
summary = f"Quadrat counts of {n} points in {nx} × {ny} cells: X² = {x2:.2f}, df = {df_chi}, {cs.fmt_p(p)}. {verdict}"
values = {"X2": x2, "df": df_chi, "p": p, "p_analytic": res["p_analytic"], "n": n, "n_quadrats": res["n_quadrats"], "expected": expected, "vmr": vmr,
          "min_count": float(np.min(counts)), "max_count": float(np.max(counts)), "n_sim": n_sim if calibration == "simulation" else 0,
          "missing_share": n_dropped / n_input if n_input else 0.0}
row_labels = [f"Row {r + 1}" for r in range(ny) for _ in range(nx)]
col_labels = [f"Column {c + 1}" for _ in range(ny) for c in range(nx)]
tables = [{"key": "counts", "title": "Counts by cell (row 1 at the bottom)", "columns": [
    {"key": "row", "label": "Row", "type": "string"}, {"key": "col", "label": "Column", "type": "string"}, {"key": "count", "label": "Count", "type": "integer"}],
    "rows": [{"row": r, "col": c, "count": float(v)} for r, c, v in zip(row_labels, col_labels, counts)]}]
charts = [cs.chart("counts", "matrix-heatmap", f"Points per cell ({expected:.1f} expected)", {
    "row": cs.col("Row", np.array(row_labels), levels=[f"Row {r + 1}" for r in range(ny - 1, -1, -1)]),
    "col": cs.col("Column", np.array(col_labels), levels=[f"Column {c + 1}" for c in range(nx)]),
    "value": cs.col("Count", counts)})]
cs.publish({
    "method": "spatial.quadrat",
    "methodVersion": "1.0.1",
    "title": "Quadrat counts",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"χ²({df_chi}) = {x2:.2f}, {cs.fmt_p(p)}",
    "statistics": [{"key": "X2", "label": "X²", "value": x2}, {"key": "df", "label": "df", "value": df_chi}, {"key": "p", "label": "p", "value": p, "format": "p"},
                   {"key": "vmr", "label": "Variance-to-mean ratio", "value": vmr}],
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [("Chi-square reference." if calibration == "chisq" else f"p from {n_sim} uniform patterns with the same count (seed {seed}).") + " A variance-to-mean ratio above 1 points to clustering, below 1 to regularity."],
    "values": values,
    "charts": charts,
})
R

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

# Quadrat counts (test of complete spatial randomness)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.quadrat 1.0.1 · spec 8347412c7cb179d4
# Dataset: sp_cells (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_cells.parquet", col_select = c("x", "y")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("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("x", "y"))  # infinite values stop the run (registry/errors.yaml)

# %% Test
# Counts in a grid of equal cells against equal expected counts: Pearson's X² (Greig-Smith 1952), or a null of
# uniform patterns from the shared random stream.
X <- "x"
Y <- "y"
coordinates <- "planar"  # planar | lonlat
nx <- as.integer(3)
ny <- as.integer(3)
alternative <- "regular"  # two_sided | clustered | regular
calibration <- "chisq"  # chisq | simulation
n_sim <- as.integer(999)
alpha <- 0.05
seed <- 42
pr <- cs_spp_project(df[[X]], df[[Y]], coordinates)
px <- pr$x
py <- pr$y
n <- length(px)
wc <- cs_spp_project(c(0, 1), c(0, 1), coordinates)
w <- cs_spp_window(px, py, "custom", wc$x[1], wc$x[2], wc$y[1], wc$y[2], names = c(X, Y))
res <- cs_spp_quadrat_test(px, py, w, nx, ny, alternative, calibration, n_sim, seed)
x2 <- res$X2
df_chi <- res$df
p <- res$p
vmr <- res$vmr
expected <- res$expected
counts <- res$counts

# %% Assumptions
small <- expected < 5 && calibration == "chisq"
assumptions <- list(
  list(key = "grid_fixed", label = "Grid chosen in advance", status = "info", detail = sprintf("A %d × %d grid. Different grids give different p-values; trying several and keeping one inflates false alarms.", nx, ny)),
  list(key = "expected_counts", label = "Enough points per cell", status = if (small) "warn" else "pass",
       detail = paste0(sprintf("%.1f points expected per cell", expected), if (small) ": too few for the chi-square reference. Use simulated patterns or a coarser grid." else ".")),
  list(key = "homogeneous", label = "Constant intensity", status = "info", detail = "Density that varies across the window looks like clustering; this test cannot tell the two apart.")
)

# %% Result
verdict <- if (p < alpha) {
  if (vmr > 1) "Counts vary more than random points would: a clustered pattern." else "Counts are more even than random points would be: a regular pattern."
} else {
  "The points are compatible with complete spatial randomness at this grid size."
}
summary <- sprintf("Quadrat counts of %d points in %d × %d cells: X² = %.2f, df = %d, %s. %s", n, nx, ny, x2, df_chi, cs_fmt_p(p), verdict)
values <- list(X2 = x2, df = df_chi, p = p, p_analytic = res$p_analytic, n = n, n_quadrats = res$n_quadrats, expected = expected, vmr = vmr,
               min_count = min(counts), max_count = max(counts), n_sim = if (calibration == "simulation") n_sim else 0L,
               missing_share = if (n_input > 0) n_dropped / n_input else 0)
row_labels <- rep(sprintf("Row %d", seq_len(ny)), each = nx)
col_labels <- rep(sprintf("Column %d", seq_len(nx)), times = ny)
tables <- list(list(key = "counts", title = "Counts by cell (row 1 at the bottom)", columns = list(
  list(key = "row", label = "Row", type = "string"), list(key = "col", label = "Column", type = "string"), list(key = "count", label = "Count", type = "integer")),
  rows = lapply(seq_along(counts), function(k) list(row = row_labels[k], col = col_labels[k], count = counts[k]))))
charts <- list(cs_chart("counts", "matrix-heatmap", sprintf("Points per cell (%.1f expected)", expected), list(
  row = cs_col("Row", row_labels, levels = sprintf("Row %d", rev(seq_len(ny)))),
  col = cs_col("Column", col_labels, levels = sprintf("Column %d", seq_len(nx))),
  value = cs_col("Count", counts))))
cs_publish(list(
  method = "spatial.quadrat",
  methodVersion = "1.0.1",
  title = "Quadrat counts",
  engine = cs_engine_info("stats"),
  n = n,
  summary = summary,
  apa = sprintf("χ²(%d) = %.2f, %s", df_chi, x2, cs_fmt_p(p)),
  statistics = list(list(key = "X2", label = "X²", value = x2), list(key = "df", label = "df", value = df_chi), list(key = "p", label = "p", value = p, format = "p"),
                    list(key = "vmr", label = "Variance-to-mean ratio", value = vmr)),
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(paste0(if (calibration == "chisq") "Chi-square reference." else sprintf("p from %d uniform patterns with the same count (seed %d).", n_sim, seed),
                      " A variance-to-mean ratio above 1 points to clustering, below 1 to regularity.")),
  values = values,
  charts = charts
))

Sources

  • Greig-Smith, P. (1952). The use of random and contiguous quadrats in the study of the structure of plant communities. Annals of Botany, 16, 293–316.
  • Baddeley, A., Rubak, E., & Turner, R. (2015). Spatial Point Patterns, ch. 6. CRC Press.

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