Voronoi tesselation in ggmap with custom color codes?

Viewed 80

I've been trying to plot a voronoi tesselation in ggmap, where the color of each block would be given hex codes such as #FFCC00. The code I've come up with so far is as below:

library(ggmap)
library(ggforce)

b <- get_map(c(2.09174, 50.52550, 7.36819, 53.68320),
             maptype = "toner",
             source = "stamen",
             zoom = 8)

lon <- c(3.76779, 5.31313, 3.48031, 3.90727, 4.15682)
lat <- c(51.2219, 52.0808, 50.7684, 51.2684, 50.9502)
hex_col <- c("#5A586E", "#47967F", "#4EB22E", "#9E82C5", "#ADCFAD")
to_plot <- data.frame(lon, lat, hex_col)


ggmap(b, base_layer = ggplot(data = to_plot,
                             aes(x = lon,
                                 y = lat))) +
  geom_voronoi_tile(aes(fill = hex_col)) +
  scale_fill_identity() +
  geom_voronoi_segment()

However, when I add the fill = hex_col parameter, an error warning comes up:

Warning message:
Computation failed in `stat_voronoi_tile()`:
There is at most one point, data or dummy, inside
the given rectangular window. Thus there are
insufficiently many points to triangulate/tessellate. 

Which I am uncertain as to how to fix, since before adding the parameter the map shows up without error. Thus my question: how do I add custom color-coded voronoi tesselations onto ggmap?

Thanks in advance!

1 Answers

The problem might be that geom_voronoi_tile expects the voronoi polygons to be closed, and your dataset lacks the outer boundaries. A quick alternative is to fall back to ggvoronoi::geom_voronoi().

library(ggmap)
library(ggforce)
library(ggvoronoi)
library(tidyverse)

b <- get_map(c(2.09174, 50.52550, 7.36819, 53.68320),
             maptype = "toner",
             source = "stamen",
             zoom = 8)

lon <- c(3.76779, 5.31313, 3.48031, 3.90727, 4.15682)
lat <- c(51.2219, 52.0808, 50.7684, 51.2684, 50.9502)
hex_col <- c("#5A586E", "#47967F", "#4EB22E", "#9E82C5", "#ADCFAD")
to_plot <- data.frame(lon, lat, hex_col)

ggmap(b, base_layer = ggplot(data = to_plot,
                             aes(x = lon,
                                 y = lat))) +
  geom_voronoi(mapping = aes(fill = hex_col), alpha = 0.5) +
  scale_fill_identity() +
  geom_voronoi_segment()

enter image description here

Related