Search code examples
rmapsr-leaflet

How to color a leaflet map by a categorical variable?


Using leaflet, how can I color the different areas based on 'NAME_ASCI' and show colors on a legend?

This works:

library(leaflet)
library(mapview)
m <- leaflet(franconia) %>%
  addProviderTiles("OpenStreetMap") %>%
  addFeatures(.)
m

But when I try to color dynamically it doesn't work. Where the color argument should go?

m <- leaflet(franconia, color = ~ RdYlBu(NAME_ASCI)) %>%
  addProviderTiles("OpenStreetMap") %>%
  addFeatures(.)
m

# With mapview I use 'zcol' to accomplish the colors

mapview(franconia, zcol = "NAME_ASCI")

Solution

  • As a starter I would suggest to have a look at the docs on colors and legends. color is an attribute of the addXXX functions.

    library(leaflet)
    library(mapview)
    
    colors <- colorRampPalette(
      RColorBrewer::brewer.pal(11, "RdYlBu")
    )(length(levels(franconia$NAME_ASCI)))
    
    pal <- leaflet::colorFactor(colors,
      domain = levels(franconia$NAME_ASCI)
    )
    
    leaflet(franconia) %>%
      addProviderTiles("OpenStreetMap") %>%
      addPolygons(
        color = ~ pal(NAME_ASCI),
        fillOpacity = 1, stroke = FALSE
      ) %>%
      addLegend(
        pal = pal,
        values = ~NAME_ASCI,
        opacity = 1
      )
    

    enter image description here