I have a simple RasterLayer in R. I added a column to the attribute table and would like to use these values in the legend of my leaflet-map. The RasterLayer looks like this:

> layer1
class      : RasterLayer 
dimensions : 38, 40, 1520  (nrow, ncol, ncell)
resolution : 1000, 1000  (x, y)
extent     : 4303000, 4343000, 3365000, 3403000  (xmin, xmax, ymin, ymax)
crs        : +proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs 
source     : memory
names      : ue65 
values     : 1, 5  (min, max)
attributes :
 ID VALUE percentage
  1     1          0
  2     2       0-15
  3     3      15-20
  4     4      20-25
  5     5        >25

And the code for making the leaflet map like this:

leaflet() %>%
  addProviderTiles('Esri.WorldImagery',group='Imagery') %>%
  addProviderTiles('Esri.WorldStreetMap', group='Streets') %>%
  addRasterImage(layer1, colors = pal, opacity = 0.7, group = "layer1") %>%
    baseGroups = c("Imagery", "Streets"),
    overlayGroups = c("layer1"),
    options = layersControlOptions(collapsed = FALSE)
  ) %>%
  addLegend(pal = pal, values = values(layer1$percentage))

I just cant figure out how to use the percentage-column from the attributes table in my legend. If I use: values = values(layer1) it shows 1-5 in the legend. Any hint would be superhelpfull!!

1 Answer 1


This works for me. Note how to get the names from the percentage column of the first set of levels of the raster, and I had to use colors= instead of pal= in addLegend, and made the pal object with pal=rainbow(5):

leaflet() %>%
 addProviderTiles('Esri.WorldImagery',group='Imagery') %>%
 addRasterImage(layer1, colors = pal, opacity = 0.7, group = "layer1") %>% 

enter image description here

  • thanks a lot for the quick answer! Don't know how you guys can solve these things so quickly. Anyways: Thanks a lot:)
    – Lenn
    Nov 30, 2019 at 14:03
  • Would have been quicker if I hadn't had to make a sample raster! I've just been teaching R/geospatial so this is all fresh in my head. And answering Qs here keeps it fresh.
    – Spacedman
    Nov 30, 2019 at 14:16
  • thanks a lot!! I hope that some day I'll also be able to answer questions and not only post a lot of questions. Do you maybe have any hint for a good ressource (I'm currently reading the Geocomputation with R and super liking it) for R/geospatial topics?
    – Lenn
    Nov 30, 2019 at 14:44
  • @Spacedeman Is there an official documentation page where I can check the code?
    – soph
    May 18, 2022 at 10:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.