rplotlegendterravoronoi

Add a legend to a voronoi diagram with field values


I try to create a map with a voronoi diagram of some climate stations. I've already created the diagram and also colored the areas in the diagram with a fitting color. Now I want a continuous legend that tells me what the colors in the areas mean.

This is what already works so far:

library(terra)

f <- system.file("ex/lux.shp", package="terra")
e <- vect(f)
x <- centroids(e)
v <- voronoi(x, e)
v <- terra::crop(v, e)

FUN <- colorRamp(c("black", "lightgrey"))
vpop <- (v$POP - min(v$POP)) / diff(range(v$POP))
vcols <- rgb(FUN(vpop), maxColorValue = 256)

plot(v, lwd = 2, col = vcols, 
     main = "Voronoi Diagram", 
     background = "beige"
     )
points(x, col = "red")

Result from Codechunk

I want a legend on the right side or on the bottom side of the plot, that matches the population numbers of the areas with the colors used in there. Since the original data has 50 Points, I want a continuous legend. This is what I've tried:

l <- c(5.8, 6.4, 49.35, 49.38)

plot(v, lwd = 2, col = vcols, 
     main = "Voronoi Diagram", 
     background = "beige",
     type = "continuous",
     range = c(min(v$POP, max(v$POP)))
     plg = list(
       ext = l,
       loc = "bottom",
       title = "Population"
       )
     )
points(x, col = "red")

I've also tried moving type and range into the list of the plg argument, but it also had no result. I've also tried using the add_legend function from terra.

add_legend("right",
           legend = c(min(v$POP), max(v$POP)),
           col = vcols)

Which also only results in two numbers floating in the map.


Solution

  • You just need to add the name of the attribute you wish to plot as the y argument to plot and set the type = "continuous".

    # Need to order the values to get the color ramp in the correct order.
    vpop <- vpop[order(vpop)]
    vcols <- rgb(FUN(vpop), maxColorValue = 256)
    
    plot(v, 
         "POP",
         lwd = 2, 
         type = "continuous",
         col = vcols, 
         main = "Voronoi Diagram", 
         background = "beige",
    )
    points(x, col = "red")
    

    plot