Search code examples
rr-leaflet

Custom static coloring for Shiny Leaflet polygons


Is there a way to build a custom qualitative color palette that maps category values to color values?

I am trying to build a basic leaflet map in Shiny that colors property parcels (polygons) by their land use (factor). Usually this is simple but I need specific colors for specific categories.

For example, parcels with a land use of 'Commercial' need to be the color '#FF4C4C'. There are about 10 land use categories.

I have tried splitting the data into different layers:

leaflet() %>%
addPolygons(data=parcels[parcels$category == 'Commercial',], fillColor = '#FF4C4C') %>%
addPolygons(data=parcels[parcels$category == 'Residential',], fillColor = '#E9E946')

And so forth but slicing the large SpatialPolygonsDataFrame ten times is slow and consumes a lot of resources. An added problem is that these categories have sub-categories that will need to be shown later, sometimes up to 20 sub-categories, and slicing the spdf 10+20 times won't do.

All of the documentation and stackoverflow questions I have found focus on defining the ranges between two or more colors, but I don't want ranges. I want an exact mapping between factor levels and specific color codes.

I hope there is a simple answer to this. I was hoping I could do something like:

lu_pal <- c('Residential' = '#E9E946', 'Commercial' = '#FF4C4C')

and find a magical function to turn that list into my palette.


Solution

  • parcels$category <- as.factor(parcel$category)
    
    factpal <- colorFactor(c("#FF4C4C", "#E9E946"), parcels$category)
    
    leaflet(parcels) %>%
      addPolygons(stroke = FALSE, smoothFactor = 0.2, fillOpacity = 1,
                  color = ~factpal(category))