if (!requireNamespace("ggforce", quietly = TRUE)) install.packages("ggforce")
library(ggforce)
library(palmerpenguins)
library(sf)
library(tidyverse)Voronoi Diagrams in R
What is a Voronoi diagram?
A Voronoi diagram divides space into regions, called cells, based on a set of points. Each cell contains every location that is closer to one particular point than to any other point. Voronoi diagrams are used in geography, meteorology and computer science for tasks like finding the nearest hospital, estimating rainfall between weather stations and classifying data.
In this lesson we draw Voronoi diagrams of penguin bill measurements, then use them to guess the species of a new penguin.
Setup
We use three packages besides the tidyverse:
ggforceadds Voronoi geoms to ggplot:geom_voronoi_tile()draws filled cells, andgeom_voronoi_segment()draws only the cell edges.palmerpenguinsprovides the penguin data.sf(simple features) does spatial calculations, like computing Voronoi cells and their centroids.
The first line installs ggforce if you don’t have it yet. requireNamespace() returns FALSE when a package isn’t installed, and ! flips that to TRUE, so install.packages() runs only when needed.
An older package, ggvoronoi, did the same job, but it was removed from CRAN in October 2023 because it depended on the retired rgeos package. You may still see it in examples online.
The data
We keep the two bill measurements and the species, drop missing values, and rename the measurements x and y to make the plotting code shorter. distinct() removes duplicate penguins, because two identical points can’t each have their own cell.
d <- penguins |>
select(starts_with("bill"), species) |>
drop_na() |>
rename(x = bill_depth_mm, y = bill_length_mm) |>
distinct()Drawing Voronoi diagrams
Cell edges
geom_voronoi_segment() draws the edges between cells. Each penguin sits inside its own cell, and the edges are exactly halfway between neighboring penguins.
ggplot(d, aes(x, y)) +
geom_voronoi_segment() +
geom_point(aes(color = species))
Filled cells
geom_voronoi_tile() fills each cell. Mapping fill = species colors each cell by its penguin’s species, so regions of the same color show where each species lives in “bill space.”
By default, fill = species would also split the data into three groups and draw a separate diagram for each species. group = -1L puts every point in one group, so we get a single diagram.
ggplot(d, aes(x, y, group = -1L)) +
geom_voronoi_tile(aes(fill = species))
Adding cell borders
color sets the border of each cell, which makes the individual cells visible.
ggplot(d, aes(x, y, group = -1L)) +
geom_voronoi_tile(aes(fill = species), color = "grey")
Showing the points
Making the fill transparent with alpha lets us draw the penguins on top of their cells.
ggplot(d, aes(x, y, group = -1L)) +
geom_voronoi_tile(aes(fill = species), color = "grey", alpha = 0.4) +
geom_point(aes(color = species))
Limiting cell size with max.radius
Cells on the outside of the data stretch to the edge of the plot, which exaggerates how much space those penguins “own.” max.radius caps how far a cell can reach from its point, so outlying cells become rounded instead.
ggplot(d, aes(x, y, group = -1L)) +
geom_voronoi_tile(aes(fill = species), color = "black",
alpha = 0.4, max.radius = 2) +
geom_point(aes(color = species))
Zooming in
coord_cartesian() zooms in without throwing away data, so the cells near the edge of the zoom are still computed from all the points. Setting limits with scale_x_continuous(limits = ...) would drop the points outside the limits before computing the diagram, which changes the cells.
ggplot(d, aes(x, y, group = -1L)) +
geom_voronoi_tile(aes(fill = species), color = "black",
alpha = 0.4, max.radius = 2) +
geom_point(aes(color = species)) +
coord_cartesian(xlim = c(16, 20), ylim = c(40, 50))
Bounding the diagram with a circle
Another way to tame the outer cells is to clip the whole diagram to a shape around the data. Here we build a circle centered on the data that’s just large enough to contain every penguin.
The center of the data
The center of the circle is the mean of each measurement.
mean_x <- mean(d$x)
mean_y <- mean(d$y)Distance from the center
Each penguin’s distance from the center comes from the Pythagorean theorem.
d <- d |>
mutate(dist2mean = sqrt((x - mean_x)^2 + (y - mean_y)^2))The circle
The radius is 5% more than the farthest penguin’s distance, so every penguin is safely inside. We draw the circle as a polygon with 100 corners; with too few corners, the polygon would cut off the farthest penguins.
rad <- 1.05 * max(d$dist2mean)
angle <- seq(0, 2 * pi, length.out = 100)
circle <- tibble(x = mean_x + rad * cos(angle),
y = mean_y + rad * sin(angle))Clipping the cells to the circle
The bound argument clips the diagram to a polygon, here our circle. It also accepts a rectangle, written as c(xmin, xmax, ymin, ymax).
ggplot(d, aes(x, y, group = -1L)) +
geom_voronoi_tile(aes(fill = species), color = "black",
alpha = 0.4, bound = circle) +
geom_point(aes(color = species))
Clipping the edges to the circle
geom_voronoi_segment() only accepts a rectangle for bound, so to draw just the edges inside the circle we draw tiles with no fill instead.
ggplot(d, aes(x, y, group = -1L)) +
geom_voronoi_tile(bound = circle, fill = NA, color = "black") +
geom_point(aes(color = species))
Classifying a new penguin
Suppose you find a new penguin with a bill depth of 15.3 mm and a bill length of 43 mm. What is its most likely species?
A guess from the picture
We add the new penguin to the diagram as a boxed X (shape = 7) and look at which colored region it lands in. We save the plot as p so we can add to it later.
newp <- tibble(x = 15.3, y = 43)
p <- ggplot(d, aes(x, y)) +
geom_voronoi_tile(aes(fill = species, group = -1L),
bound = circle, color = "grey") +
scale_fill_viridis_d(option = "D", alpha = 0.5) +
geom_point(aes(color = species)) +
scale_color_viridis_d(option = "H", alpha = 0.5) +
geom_point(data = newp, aes(x, y), shape = 7) +
coord_cartesian(xlim = c(12, 25), ylim = c(35, 50))
p
Classifying with sf
To answer the question with code instead of by eye, we compute the Voronoi cells ourselves with the sf package. Then we find the cell whose centroid (its center of mass) is closest to the new penguin.
The points as sf
st_as_sf() turns the x and y columns into point geometries. remove = FALSE keeps the original x and y columns too. These are measurements, not map coordinates, so we don’t set a coordinate reference system (CRS); without one, sf does ordinary flat-plane geometry.
pts <- d |>
select(x, y, species) |>
st_as_sf(coords = c("x", "y"), remove = FALSE)The circle as an sf polygon
We turn the circle’s points into a single polygon: st_combine() joins the points into one shape, and st_cast() connects them into a polygon.
c_poly <- circle |>
st_as_sf(coords = c("x", "y")) |>
summarize(geometry = st_combine(geometry)) |>
st_cast("POLYGON")The Voronoi cells
st_voronoi() computes the cells. It needs all the points combined into one geometry, which is what st_combine() does.
vor <- st_voronoi(st_combine(pts))Extracting the polygons
st_voronoi() returns a single GEOMETRYCOLLECTION, which many functions can’t work with. st_collection_extract() pulls out the individual cell polygons, and st_sf() stores them in a data frame. We name the geometry column geometry explicitly, because different versions of sf choose different default names.
vor_poly <- st_sf(geometry = st_collection_extract(vor))Cropping the cells to the circle
st_intersection() keeps only the part of each cell that lies inside the circle, just like bound = circle did in ggplot.
vor_poly <- st_intersection(vor_poly, c_poly)Matching each cell to its penguin
st_voronoi() does not return the cells in the same order as the points, so we can’t simply paste the two tables together with cbind(). Instead, st_join() matches each cell to the penguin that lies inside it, adding that penguin’s x, y and species.
cells <- st_join(vor_poly, pts)Plotting the cells with sf
geom_sf() draws sf geometries directly. This plot should match the clipped diagram we drew with ggforce.
ggplot(cells) +
geom_sf(aes(fill = species), color = "grey", alpha = 0.5) +
geom_point(aes(x, y, color = species))
The centroid of each cell
st_centroid() finds the center of mass of each cell, and st_coordinates() extracts its x and y coordinates as numbers. st_drop_geometry() then turns the result back into an ordinary tibble.
cntrd <- cells |>
mutate(centroid = st_centroid(geometry)) |>
mutate(centroid_x = st_coordinates(centroid)[, 1],
centroid_y = st_coordinates(centroid)[, 2]) |>
st_drop_geometry() |>
select(x, y, species, centroid_x, centroid_y) |>
as_tibble()Plotting the centroids
Each centroid (marked with an x) sits close to its penguin, but not exactly on it, especially in large outer cells.
p + geom_point(data = cntrd, aes(centroid_x, centroid_y), shape = 4)
The nearest centroid
We compute the distance from the new penguin to every centroid and keep the closest one.
nearest_cntrd <- cntrd |>
mutate(dist = sqrt((centroid_x - newp$x)^2 + (centroid_y - newp$y)^2)) |>
arrange(dist) |>
slice_head()The predicted species
The species of the cell with the nearest centroid is our prediction.
nearest_cntrd |> select(species)# A tibble: 1 × 1
species
<fct>
1 Gentoo
A simpler check: which cell is the new penguin in?
The new penguin lies in exactly one Voronoi cell, and that cell belongs to its nearest neighbor in the data. So the species of that cell is the prediction a 1-nearest-neighbor classifier would make. st_intersects() finds the cell that contains the new point.
newp_sf <- st_as_sf(newp, coords = c("x", "y"))
cells |>
filter(lengths(st_intersects(geometry, newp_sf)) > 0) |>
st_drop_geometry() |>
select(species) species
1 Gentoo
The two methods usually agree. They can disagree for a new point near the edge between two cells, because the nearest centroid isn’t always the centroid of the cell the point is in.
Testing the classifier
So far we predicted the species of one made-up penguin, and we had no way to check whether the answer was right. To measure how good the classifier really is, we hide some penguins from it, build the Voronoi diagram from the rest, and see how often it predicts the hidden penguins’ species correctly.
Splitting into training and testing sets
The training set is the data the classifier learns from: here, the penguins whose cells make up the diagram. The testing set is held back, so we know the right answers but the classifier has never seen them.
set.seed() makes the random split the same every time the document renders. slice_sample(prop = 0.7) picks 70% of the penguins for training, and anti_join() keeps the rest for testing.
set.seed(309)
train <- d |> slice_sample(prop = 0.7)
test <- d |> anti_join(train, by = c("x", "y", "species"))
nrow(train)[1] 236
nrow(test)[1] 102
Building the diagram from the training set
These are the same steps as before, applied only to the training penguins: compute the cells, crop them to the circle, match each cell to its penguin, and find each cell’s centroid.
train_pts <- train |>
select(x, y, species) |>
st_as_sf(coords = c("x", "y"), remove = FALSE)
train_cells <- st_sf(geometry = st_collection_extract(st_voronoi(st_combine(train_pts)))) |>
st_intersection(c_poly) |>
st_join(train_pts)
train_cntrd <- train_cells |>
mutate(centroid = st_centroid(geometry)) |>
mutate(centroid_x = st_coordinates(centroid)[, 1],
centroid_y = st_coordinates(centroid)[, 2]) |>
st_drop_geometry() |>
select(species, centroid_x, centroid_y) |>
as_tibble()A prediction function
A function packages the nearest-centroid steps from earlier so we can reuse them on any penguin. Given a bill depth x and bill length y, it computes the distance to every training centroid and returns the species of the closest one.
predict_species <- function(x, y) {
train_cntrd |>
mutate(dist = sqrt((centroid_x - x)^2 + (centroid_y - y)^2)) |>
slice_min(dist, n = 1) |>
pull(species) |>
as.character()
}
# try it on the new penguin from before
predict_species(15.3, 43)[1] "Gentoo"
Predicting every test penguin
map2_chr() runs predict_species() once for each row of test, passing that row’s x and y, and collects the answers into a new column. (It’s map2 because the function takes two inputs, and _chr because each answer is text.)
test <- test |>
mutate(predicted = map2_chr(x, y, predict_species))
test |> select(x, y, species, predicted) |> head()# A tibble: 6 × 4
x y species predicted
<dbl> <dbl> <fct> <chr>
1 18 40.3 Adelie Adelie
2 18.1 34.1 Adelie Adelie
3 17.3 37.8 Adelie Adelie
4 17.6 41.1 Adelie Adelie
5 21.1 34.6 Adelie Adelie
6 21.5 46 Adelie Chinstrap
Accuracy
The accuracy is the fraction of test penguins whose predicted species matches their real one. mean() of TRUE/FALSE values gives that fraction, because R counts TRUE as 1 and FALSE as 0.
test |>
summarize(accuracy = mean(predicted == species))# A tibble: 1 × 1
accuracy
<dbl>
1 0.922
Where it goes wrong
A confusion matrix counts each combination of real and predicted species. The diagonal (where species and predicted match) holds the correct predictions; everything else is a mistake.
test |>
count(species, predicted) |>
pivot_wider(names_from = predicted, values_from = n, values_fill = 0)# A tibble: 3 × 4
species Adelie Chinstrap Gentoo
<fct> <int> <int> <int>
1 Adelie 45 1 0
2 Chinstrap 4 20 1
3 Gentoo 0 2 29
Most mistakes are between Adelie and Chinstrap, or Chinstrap and Gentoo: species whose clouds of points overlap in the plots above. Adelie and Gentoo, which sit far apart, are rarely confused.
Comparing with the “which cell is it in?” rule
Earlier we saw a second way to predict: use the species of the cell the new penguin falls in. Every point in a penguin’s cell is closer to that penguin than to any other, so this is the same as using the species of the nearest training penguin: a 1-nearest-neighbor classifier. st_nearest_feature() finds, for each test penguin, the row number of the nearest training penguin.
test_pts <- test |>
st_as_sf(coords = c("x", "y"), remove = FALSE)
nearest <- st_nearest_feature(test_pts, train_pts)
test <- test |>
mutate(cell_species = as.character(train_pts$species[nearest]))
test |>
summarize(
nearest_centroid = mean(predicted == species),
containing_cell = mean(cell_species == species)
)# A tibble: 1 × 2
nearest_centroid containing_cell
<dbl> <dbl>
1 0.922 0.931
The two rules usually score about the same. Because the split is random, the exact numbers change with the seed; try a few different values in set.seed() and see how much the accuracy moves.