Search code examples
rleafletr-sf

How to change NA values to NULL in a leaflet choropleth map?


I am trying to map a categorical variable that has NA values. I would like the NA values to appear as transparent on the map but they seem to show up as black.

library(sf)
library(leaflet)
library(tidyverse)

demo(nc, ask = FALSE, echo = FALSE)

# Add arbitrary factor column

nc <- nc %>% 
  mutate(
    factor_col = rep(c("A", "B", "C", "D", NA),20)
  )


factpal <- colorFactor(topo.colors(4), nc$factor_col, na.color = NA)
previewColors(factpal, unique(nc$factor_col))

leaflet(nc) %>%
  addPolygons(stroke = FALSE, smoothFactor = 0.2, fillOpacity = 1,
              color = ~factpal(factor_col))

It appears that the palette is correct

enter image description here

But when I render the map, the NA values show up black instead.

enter image description here

Any help would be greatly appreciated. Thanks


Solution

  • Here's a somewhat hacky way to do it, but it works. You can add a function for fillOpacity that returns 0 for NA values, and 1 for all else.

    factop <- function(x) {
      ifelse(is.na(x), 0, 1)
    }
    
    leaflet(nc) %>%
      addPolygons(stroke = FALSE, smoothFactor = 0.2, fillOpacity = ~factop(factor_col),
                  color = ~factpal(factor_col))