79770544

Date: 2025-09-20 20:34:00
Score: 2.5
Natty:
Report link

Thank you Tim,

But this is not exactly what I am looking for. In fact, my real code is more complex, the example I posted was just a simplification. I am working with time series stacked in a multilayer SpatRaster (dozens of layers). With plet() you can easily navigate through the layers, and for comparison it is essential to use a fixed reference color palette.

plet() handles multilayer SpatRasters very well: plotting the different layers is just a matter of passing an argument. However, leaflet does not accept multilayer rasters directly, so to plot them you need to split the stack and add each layer one by one in a loop.

The problem is with the col argument. In terra 1.7.7x, plet(col=) accepted the output of colorNumeric and painted each layer with the correct range of values from that palette. In terra 1.8.x this no longer works.

There should be a way to provide a value–color mapping object to plet(col=), but I have not been able to figure it out.

Below I attach an extension of my previous example, which in terra 1.7.7x produces exactly the expected map:

enter image description here

ibrary(terra)
library(leaflet) 

# data
f <- system.file("ex/elev.tif", package="terra") 
r <- rast(f) # to raster
r
# Color palette
   raster_colors = c("red", "yellow", "blue")
   zlim_v <- c(-100, 1000) # 
#
# 2) Construir multilayer: r, r+400, r-200
r_plus400 <- r + 400
r_minus200 <- r - 200
r_multi <- rast(c(`Topo (m)` = r,
             `Topo +400 m` = r_plus400,
             `Topo -200 m` = r_minus200))

#' Create a color palette with colorNumeric function
   mypal <- colorNumeric(palette = raster_colors, # color gradient to use
                          domain = zlim_v,        # range of the numeric variable
                          na.color = NA           # no color for NA values
                          )
## Create map with a multilayer raster and a custom color palette
   p_topo <- plet(r_multi,                # raster file
              y = c(1:nlyr(r_multi)),   # raster layers
              tiles="OpenStreetMap.Mapnik",
              alpha=0.7,              # opacity
              col = mypal,        # color palette
              legend = NULL           # no legend
             )  %>%
         addLegend(
              pal = mypal,          # legend colors
              values = zlim_v,          # legend values
              title = "topo (m)",        # legend title
              opacity = 0.7             # legend opacity
             )

p_topo
Reasons:
  • Blacklisted phrase (0.5): Thank you
  • Blacklisted phrase (2): I am looking for
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Ignacio Marzan