Skip to main content

13. Point pattern analysis

Packages

library(MASS)      # Bandwidth estimation for kernel density estimation
library(terra)     # Reading and manipulating raster data
library(sf)        # Reading and manipulating vector data
library(dplyr)     # Manipulating data.frames
library(ggplot2)   # Visualization
library(spatstat)  # Point Pattern Analysis
library(SpatialKDE) # Kernel density estimation
theme_set(theme_light())

The MASS package is loaded first because it also contains a function named select(). Packages loaded later mask functions with the same name from packages loaded earlier. Loading MASS before dplyr ensures that select() refers to dplyr::select().

The spatstat package provides a wide range of methods for the statistical analysis of spatial point patterns, including

  • kernel estimation of density/intensity
  • quadrat counting and clustering indices
  • detection of clustering using Ripley’s K-function
  • spatial logistic regression
  • model-fitting
  • Monte Carlo tests

Data

We are going to use wildfire records of the Kamloops Fire Centre in British Columbia, Canada (BC Wildfire Service, 2026). The file kamloops.gpkg contains two layers: the boundary of the fire centre (aoi) and the locations of all fires recorded between 1970 and 2024 (fires), with the following attributes.

Attribute Type Description
year integer Year of the fire: 1970, 1971, …, 2024
cause character General cause of the fire: Lightning, Person, Unknown
size_ha number Final size of the fire (burned area) in hectares
ignition date Ignition date of the fire

Both layers are in the BC Albers projection (EPSG:3005), which is defined in meters.

# study area (observation window)
aoi <- st_read("data/kamloops.gpkg", layer = "aoi", quiet = TRUE)

# fire locations
fires_sf <- st_read("data/kamloops.gpkg", layer = "fires", quiet = TRUE)

# remove fires with zero burned areas
fires_sf <- filter(fires_sf, size_ha > 0)

head(fires_sf)
Simple feature collection with 6 features and 4 fields
Geometry type: POINT
Dimension:     XY
Bounding box:  xmin: 1332252 ymin: 490102.6 xmax: 1495245 ymax: 644967.8
Projected CRS: NAD83 / BC Albers
  year     cause size_ha   ignition                     geom
1 1970    Person     6.0 1970-05-16 POINT (1332252 644967.8)
2 1970 Lightning     0.1 1970-07-16 POINT (1449345 499270.6)
3 1970 Lightning     0.2 1970-07-16 POINT (1495245 490102.6)
4 1970    Person     0.1 1970-07-21 POINT (1467539 500004.1)
5 1970    Person     0.1 1970-08-02 POINT (1462495 519409.8)
6 1970    Person     0.1 1970-08-04 POINT (1461193 533802.1)

For plotting with ggplot2 and for kernel density estimation, we also need the coordinates and attributes in a regular data.frame.

fires_df <- data.frame(st_coordinates(fires_sf), st_drop_geometry(fires_sf)) |>
  rename(x = X, y = Y)

Convert sf to ppp

Functions in the spatstat package work with point pattern objects of class ppp (point pattern dataset). A ppp object stores the point coordinates together with an observation window, i.e., the area in which points could have occurred. We convert the sf object with as.ppp(), which takes a matrix of coordinates and a window. As the window, we use the boundary of the fire centre (aoi), because the dataset only contains fires within the Kamloops Fire Centre. The attributes are added as marks. To keep the numbers small, we convert the coordinates from meters to kilometers with rescale(). All distances and areas computed with spatstat are therefore in km and km², respectively.

fires_ppp <- as.ppp(st_coordinates(fires_sf), W = as.owin(st_geometry(aoi)))
marks(fires_ppp) <- st_drop_geometry(fires_sf)

# rescale coordinates from m to km
unitname(fires_ppp) <- c("meter", "meters")
fires_ppp <- rescale(fires_ppp, 1000, "km")
fires_ppp
Marked planar point pattern: 28567 points
Mark variables: year, cause, size_ha, ignition 
window: polygonal boundary
enclosing rectangle: [1159.9468, 1556.6472] x [457.4887, 890.4348] km

Geographic distribution

Centrographic statistics are tools used to analyze geographic distributions by measuring the center, dispersion and directional trend of a spatial arrangement (Grekousis, 2020).

Centroid

There are several ways to describe the centroid or center of the geographic distribution. The mean center can easily be calculated by averaging the coordinates. We can use the summarize() function from the dplyr package to calculate the mean x and y coordinate.

centroid <- summarize(fires_df,
                      x = mean(x),
                      y = mean(y))

ggplot(centroid) + 
  geom_point(size=2, aes(x = x, y = y)) +
  geom_point(data=fires_df, aes(x=x, y=y), alpha=0.01) +
  geom_sf(data=aoi, aes(), fill=NA)

The figure above shows all fire locations in the background (high transparency) and the overall mean represented by the bold point. The overall mean location is not very meaningful. What is often done is to see how the geographic center of the distribution changes over time or with different factors. Use the group_by() function to calculate the mean by year (see Lab 3 for data manipulation with dplyr).

centroids <- fires_df |>
  group_by(year) |> 
  summarize(x = mean(x),
            y = mean(y))

ggplot(centroids) + 
  geom_point(size=2, aes(x = x, y = y, col=year)) +
  geom_point(data=fires_df, aes(x=x, y=y), alpha=0.01) +
  geom_sf(data=aoi, aes(), fill=NA)

Fires actually do not represent points but areas, and those areas can vary substantially. To account for burned area size, we can calculate a weighted average location, using final burned area as the weight. Compare these weighted centroids with the unweighted centroids above to see how accounting for fire size changes the estimated geographic center in each year. Large shifts between weighted and unweighted centroids indicate that a few large fires lie away from the bulk of the fires.

centroids.w <- fires_df |>
  group_by(year) |> 
  summarize(x = weighted.mean(x, w=size_ha),
            y = weighted.mean(y, w=size_ha))

ggplot(centroids.w) + 
  geom_point(size=2, aes(x = x, y = y, col=year)) +
  geom_point(data=fires_df, aes(x=x, y=y), alpha=0.01) +
  geom_sf(data=aoi, aes(), fill=NA)

Dispersion

The dispersion or spread of the geographic distribution can be described with the standard distance (circle) or (better) standard deviational ellipses. The standard deviational ellipse measures the standard distance separately along the direction of greatest spread and perpendicular to it, and thus describes both the dispersion and the orientation of the distribution. The feature is available in ArcGIS, QGIS, and in the R package sfdep. Alternatively, ggplot2 can be used to fit and visualize ellipses using a multi-normal distribution.

ggplot(fires_df) + 
  geom_point(aes(x = x, y = y), alpha=0.01) +
  geom_point(data=centroid, aes(x=x, y=y), color=4) +
  stat_ellipse(aes(x = x, y = y),
               type = "norm",
               level=pchisq(1, df=2),
               color=4) +
  geom_sf(data=aoi, fill=NA)

The argument level sets the proportion of points enclosed by the ellipse, assuming a bivariate normal distribution. Here, we draw the ellipse at one standard deviation. Unlike in one dimension, where one standard deviation covers 68% of the values, a one-standard-deviation ellipse encloses only 39% of the points (level=pchisq(1, df=2)).

Distance methods

Distance-based methods of Point Pattern Analysis use the distances among events and describe second-order effects. Such methods include the nearest neighbor method, the G and F distance functions, and Ripley’s K-function. There are different kinds of distances that can be measured in a point pattern (Baddeley et al., 2015):

  • pairwise distances \(d_{ij} = \lVert x_i - x_j \rVert\) between all distinct pairs of points \(x_i\) and \(x_j\) (\(i \neq j\)) in the pattern

  • nearest neighbor distances \(t_i = \min_{j \neq i} d_{ij}\), the distance from each point \(x_i\) to its nearest neighbor

  • empty space distances \(d(u) = \min_j \lVert u - x_j \rVert\), the distance from a fixed reference location \(u\) in the window to the nearest data point

Fires from different years often occur at the same or nearby locations, and pooling all years would mix patterns that may differ between years. We therefore look at the point pattern of a single year only. With the subset() function, we can select points based on the values of their attributes/marks. Here, we select all fires of 1970, the year with the most fires in the time series.

fires_1970 <- subset(fires_ppp, year==1970)

Pairwise distance

The pairwise distances can be calculated with the pairdist() function of the spatstat package. The result is a matrix of pairwise distances.

M <- pairdist(fires_1970)
M[1:5, 1:5]
         [,1]      [,2]      [,3]      [,4]      [,5]
[1,]   0.0000 186.91828 224.83341 198.28546 180.90930
[2,] 186.9183   0.00000  46.80700  18.20909  24.05251
[3,] 224.8334  46.80700   0.00000  29.42219  43.94844
[4,] 198.2855  18.20909  29.42219   0.00000  20.05046
[5,] 180.9093  24.05251  43.94844  20.05046   0.00000

We can look at the frequency distribution of the pairwise distances. The square matrix contains the distances twice (point A to B and point B to A) as well as the diagonal elements (distance of the points to themselves). So, we extract only the distances of the upper triangle of the matrix using upper.tri().

Mup <- M[upper.tri(M, diag=F)]
hist(Mup, xlab="Pairwise distance (km)", main="")

The mean pairwise distance is 129.54 km, and 50% of all point pairs are between 79.66 and 173.71 km apart.

summary(Mup)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   0.00   79.66  125.58  129.54  173.71  426.71 

Nearest neighbor distance

The nearest neighbor distances can be calculated with the nndist() function of the spatstat package.

N <- nndist(fires_1970)
head(N)
[1] 3.4786980 3.2936359 7.0897669 1.6668536 0.4446049 2.3849839

The result is a vector with a length corresponding to the number of events. The frequency distribution of the nearest neighbor distances is right-skewed: most fires have a neighbor close by, and only a few are far away from the next fire.

hist(N, xlab="Nearest neighbor distance (km)", main="")

On average, the nearest neighbor was 2.47 km away, and 50% of the data points had neighbors that were less than 1.77 km away.

summary(N)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
 0.0000  0.8438  1.7653  2.4658  3.3103 23.2078 

The minimum distance of 0 km results from fires with identical coordinates, which spatstat reports as duplicated points.

Nearest neighbor distances are right-skewed also for completely random point patterns. To assess whether the events are clustered, the Clark-Evans index \(R\) compares the observed mean nearest neighbor distance with the mean expected under complete spatial randomness (CSR), \(0.5/\sqrt{\lambda}\), where \(\lambda\) is the intensity (number of events per unit area). Values of \(R < 1\) indicate clustering, and values of \(R > 1\) indicate regularity.

clarkevans(fires_1970, correction = "none")
[1] 0.7002065

The observed mean nearest neighbor distance of the fires in 1970 is shorter than expected for a random pattern (\(R\) = 0.7), which indicates that the fires are spatially clustered.

G-Function

The spatial arrangements of points can be described via the cumulative distribution function of the nearest-neighbor distances, also called the G-Function. The G-Function can be computed from a point pattern object using the Gest() function. The result of Gest is an object of class fv, containing several estimates of the function using different edge corrections, together with the theoretical value for a homogeneous Poisson process with the same average intensity.

Gs <- Gest(fires_1970)
plot(Gs)

The plot shows three very similar estimates of the G Function and the theoretical function for complete spatial randomness. The empirical curve lies above the theoretical curve for a completely random pattern, indicating that the nearest-neighbor distances in the data are shorter than expected for a completely random pattern. This is consistent with clustering.

Specifically, the curve shows that \(\hat{G}(r)=0.5\) is achieved at about \(r\) = 1.8 km, which means that 50% of the nearest-neighbor distances were 1.8 km and shorter.

K-Function

A very popular technique for analyzing spatial correlation in point patterns is the K-function also known as Ripley’s K-function. The empirical K-function \(\hat{K}(r)\) is the cumulative average number of data points lying within a distance \(r\) of a typical data point, corrected for edge effects, and standardized by dividing by the intensity. The standardization and edge correction make it possible to compare point patterns with different numbers of points, observed in different windows. The Kest() function of the spatstat package provides several correction methods. By default, Ripley’s isotropic correction (\(\hat{K}_{iso}\)), the border method (\(\hat{K}_{bord}\)), and the translation correction (\(\hat{K}_{trans}\)) are shown (see ?Kest for more info and references).

Ks <- Kest(fires_1970)
plot(Ks)

\(K\) values greater than the theoretical \(K_{pois}(r)\) of a completely random (Poisson) pattern indicate clustering of points at a given distance \(r\); \(K\) values less than \(K_{pois}(r)\) indicate regularity (dispersion) of points at a given distance. In our example, the empirical curves lie above the theoretical curve at all distances.

Even a completely random pattern produces an empirical K-function that deviates somewhat from \(K_{pois}(r)\). To assess whether the deviation is larger than expected by chance, we can use a Monte Carlo test. The envelope() function simulates a number of random point patterns with the same intensity and in the same window as the observed pattern, and calculates the K-function for each of them. The minimum and maximum of the simulated K-functions form the envelope (grey area). With 39 simulations, an observed curve outside the envelope at a given distance \(r\) corresponds to a significance level of 5%: under complete spatial randomness, the probability that the observed curve lies above or below all 39 simulated curves is 2/40 = 0.05 (see ?envelope). Note that this significance level applies to each distance \(r\) separately, not to the curve as a whole.

set.seed(42)
Ks_env <- envelope(fires_1970, Kest, nsim = 39, verbose = FALSE)
plot(Ks_env)

The observed K-function lies above the envelope at almost all distances, which indicates that the fires in 1970 are significantly clustered.

The K-function assumes that the point pattern is homogeneous, i.e., that the intensity is constant across the study area. Fire ignitions, however, are not equally likely everywhere. They depend, for example, on population density, road access, and the distribution of forests. Such variation in intensity (a first-order effect) also produces apparent clustering in the K-function, even if the fires occur independently of each other. The K-function alone therefore cannot distinguish between clustering due to interaction among events (second-order effects) and clustering due to a varying intensity. The Kinhom() function of the spatstat package estimates an inhomogeneous K-function that accounts for a spatially varying intensity (see ?Kinhom).

Density methods

Density-based methods of Point Pattern Analysis use the intensity of event occurrence across space and describe primarily first-order effects. In this section, we use the fires of all years.

Quadrat Count

A simple approach to measure intensity is to divide the study area into grid cells and count the number of events in each cell. Besides spatstat, this can be done with the rasterize() function of the terra package, which produces a raster that can be exported to other GIS and remote sensing software.

rasterize() requires a template raster that defines the grid. We create an empty raster with 5 x 5 km cells from the extent of the study area. Since the CRS is defined in meters, the cell size is 5000 m. align() rounds the extent outward to multiples of the cell size.

extent <- align(ext(aoi), 5000)
ras <- rast(extent, resolution = 5000, crs = crs(fires_sf))
ras
class       : SpatRaster
size        : 88, 81, 1  (nrow, ncol, nlyr)
resolution  : 5000, 5000  (x, y)
extent      : 1155000, 1560000, 455000, 895000  (xmin, xmax, ymin, ymax)
coord. ref. : NAD83 / BC Albers (EPSG:3005)

For each cell, rasterize() collects the points inside the cell in an atomic R vector (a non-spatial vector) and summarizes this vector with the function given in fun. With fun = "length", the result is the number of fires per cell. Cells without fires are NA, unless a background value is set (here 0). Since this also sets the cells outside the study area to 0, we use mask() to set them back to NA.

fire_count <- terra::rasterize(fires_sf, ras, fun = "length", background = 0)
fire_count <- mask(fire_count, aoi)
plot(fire_count)

The counts depend on the cell size: larger cells contain more fires. To obtain the intensity (number of fires per km²), we divide the counts by the cell area in km². Cells along the boundary lie partly outside the study area, so their intensity is underestimated.

cell_area <- prod(res(fire_count)) / 1e6  # 5000 m x 5000 m = 25 km²
fire_count_intensity <- fire_count / cell_area
plot(fire_count_intensity)

Kernel estimation

Kernel density methods estimate the localized intensity (density) of events based on a moving window. Unlike with the fixed quadrats the subregions overlap with the moving windows yielding smoother density surfaces. The shape and size of the moving window, as well as weights are defined by the Kernel function (e.g., Gaussian, quartic).

The outcome of the Kernel estimation depends mainly on the bandwidth \(h\), and much less on the choice of the Kernel function. There are different ways to select an appropriate value for \(h\), but it is important to note that there is a good deal of subjectivity involved. Often \(h\) is determined by trial and error and visual assessment of the output. Grekousis (2020) suggests the use of Ripley’s \(K\) (or its transformed L function) to set the bandwidth based on the clustering or dispersion distances. Below, we use a simple rule of thumb from Venables and Ripley (2002, p. 130) as a starting point. The rule is available with the bandwidth.nrd() function in the MASS package. Since fires_df contains the original coordinates, the bandwidths are in meters.

bw_x <- bandwidth.nrd(fires_df$x)
bw_y <- bandwidth.nrd(fires_df$y)
c(bw_x, bw_y)
[1] 34435.56 42991.66

We can then calculate the Kernel density raster using kde() from the SpatialKDE package. By default, kde() uses a quartic kernel, for which the bandwidth is the search radius: each fire contributes to the density of all cells within this distance, with weights decreasing from the center to the edge of the kernel. Because the rule of thumb above is meant for a Gaussian kernel, we convert it to a search radius for the quartic kernel by multiplying it by 0.71 (see the note below).

bw_quartic <- sqrt(8) / 4 * mean(c(bw_x, bw_y))
bw_quartic
[1] 27374.65

The bandwidth from bandwidth.nrd() corresponds to four standard deviations of a Gaussian kernel. A two-dimensional quartic kernel with radius \(r\) has a standard deviation of \(r/\sqrt{8}\) in the x and y direction. To obtain the same amount of smoothing, we set both standard deviations equal and obtain \(r = \sqrt{8}/4 \cdot h \approx 0.71 \, h\). Since the rule of thumb itself is only a starting point, this conversion is not critical, but it makes the results of the two kernels comparable.

The kde() function estimates the density on a grid of cells. We create this grid with create_raster(), using the same cell size as for the quadrat counts (10 km). The resulting raster is then passed to kde() together with the bandwidth and the kernel function.

grid <- SpatialKDE::create_raster(fires_sf, cell_size = res(ras)[1])
fire_kde <- SpatialKDE::kde(fires_sf, 
                            band_width = bw_quartic, grid = grid,
                            kernel = "quartic", quiet = TRUE)

# convert to terra raster and mask cells outside the study area
fire_kde <- mask(rast(fire_kde), aoi)

From weights to intensity: Each fire adds a weight of 1 at its location, which decreases to 0 at the search radius. The value of each cell is the sum of these weights, i.e., a distance-weighted count of the fires around the cell. These values depend on the bandwidth: a larger search radius includes more fires and yields larger values. To obtain the intensity (number of fires per km²), we divide by the volume of a single kernel, which is \(\pi r^2/3\) for a quartic kernel with radius \(r\). Because \(r\) is in meters, this gives fires per m², which we multiply by 106 to obtain fires per km². Since the dataset covers all years, the result is the number of fires per km² over the whole period 1970–2024.

fire_intensity <- fire_kde / (pi * bw_quartic^2 / 3) * 1e6  # fires per km²
plot(fire_intensity)

Both maps show the intensity in fires per km², so we can compare them directly. To make the colors comparable, we use the same value range for both maps. A few quadrats have much higher intensities than the rest, which would compress the colors of all other cells. We therefore stretch the colors from 0 to the maximum of the kernel estimate. Quadrats with higher values are shown in the color of the maximum (fill_range = TRUE).

zlim <- c(0, global(fire_intensity, "max", na.rm = TRUE)[1, 1])

par(mfrow = c(1, 2))
plot(fire_count_intensity, range = zlim, fill_range = TRUE, main = "Quadrat count")
plot(fire_intensity, range = zlim, fill_range = TRUE, main = "Kernel estimation")

par(mfrow = c(1, 1))

The quadrat counts vary strongly from cell to cell, and single cells with many fires stand out. The kernel estimate spreads each fire over the search radius, which smooths out these local peaks and yields lower maximum values, but shows the regional pattern of fire intensity more clearly.

NoteEdge effects

Near the boundary of the study area, part of each kernel falls outside the study area. Because the dataset contains no fires there, the intensity along the boundary is underestimated. Masking the raster only hides the cells outside the study area; it does not correct this edge effect.

Kernel maps with ggplot2

The ggplot2 package also estimates kernel density maps (based on MASS::kde2d()). With facet_wrap(), we can estimate and map the intensity separately for each cause of fire.

ggplot() +
  stat_density_2d(data = fires_df,
                  aes(x = x, y = y, fill = after_stat(count) * 1e6),  # per km²
                  n = 80, h = c(bw_x, bw_y), geom = "tile", contour = FALSE) +
  scale_fill_gradient(low = "white", high = "red", name = "Fires per km²") +
  geom_sf(data = aoi, fill = NA) +
  facet_wrap(~ cause) +
  coord_sf(datum = st_crs(3005))

The maps show that the spatial pattern of fires differs by cause. Lightning fires are spread more widely across the study area, with the highest intensity in the east. Human-caused fires are concentrated in a few hotspots in the central and southern parts of the study area, where most people live and where roads give access to the forests. Fires of unknown cause are rare, so their intensity is low everywhere. Note that all maps use the same bandwidth, which was estimated from all fires.

References

Baddeley, A., Rubak, E., Turner, R., 2015. Spatial point patterns: Methodology and applications with R. Chapman and Hall/CRC, Boca Raton. https://doi.org/10.1201/b19708
BC Wildfire Service, 2026. BC wildfire fire incident locations – historical. URL https://catalogue.data.gov.bc.ca/dataset/bc-wildfire-fire-incident-locations-historical (accessed 11.19.2026).
Grekousis, G., 2020. Analyzing geographic distributions and point patterns, in: Spatial Analysis Methods and Practice: Describe – Explore – Explain Through GIS. Cambridge University Press, Cambridge, pp. 147–206. https://doi.org/10.1017/9781108614528.004
Venables, W.N., Ripley, B.D., 2002. Modern applied statistics with S, 4th ed. Springer, New York. https://doi.org/10.1007/978-0-387-21706-2