Fill Voronoi polygons with color gradient?

Viewed 55

I have been trying to fill Voronoi polygons/tiles with raster grob objects, but I have not been able to find a way to do it. This is a sample of the code for the Voronoi ggplot

library(ggplot2) 
library(grid)
library(RColorBrewer)
library(ggmap)
library(ggvoronoi)
library(raster)

    # Get the location of the city in the map
    bcn_map <- get_googlemap(center = "Plaza España, Barcelona",zoom = 14,key="xxx")
    bounds <- as.numeric(attr(bcn_map,"bb"))
    set.seed(500)
    num <- geocode("Plaza España, Barcelona")
   # Create a dummy data frame with random values 
    df <- round(data.frame(
      x = jitter(rep(num$lon,200), amount = .03),
      y = jitter(rep( num$lat,200), amount = .03)
    ), digits = 5)
    
    # Plot the map with the Voronoi layer
    ggmap(bcn_map,base_layer = ggplot(data=df,aes(x,y))) +
      coord_map(ylim=bounds[c(1,3)],xlim=bounds[c(2,4)]) +
      theme_minimal() +
      theme(axis.text=element_blank(),
            axis.title=element_blank())+
      geom_path(stat="voronoi",alpha=0.2 ,size=2,colour = "pink") +
      geom_point(color="blue",size=.25)

And this is the raster object I want to include, fitting the tiles in the Voronoi diagram:

make_gradient <- function(deg = 45, n = 100, cols = blues9) {
  cols <- colorRampPalette(cols)(n + 1)
  rad <- deg / (180 / pi)
  mat <- matrix(
    data = rep(seq(0, 1, length.out = n) * cos(rad), n),
    byrow = TRUE,
    ncol = n
  ) +
    matrix(
      data = rep(seq(0, 1, length.out = n) * sin(rad), n),
      byrow = FALSE,
      ncol = n
    )
  mat <- mat - min(mat)
  mat <- mat / max(mat)
  mat <- 1 + mat * n
  mat <- matrix(data = cols[round(mat)], ncol = n)
  grid::rasterGrob(
    image = mat,
    width = unit(1, "npc"),
    height = unit(1, "npc"), 
    interpolate = TRUE
  )
}

#Set pallete
cc <- palette(c("#333C83","#F24A72","white","#FDAF75"))

# Create gradient with the colors defined before
raster.grob <- make_gradient(
  deg = 90, n = 100, cols = cc
)

I don't know if this is possible in R, but thanks in advance for the help.

0 Answers
Related