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

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

Any help would be greatly appreciated. Thanks
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))
You can assign an alpha value on the specific hex color use in the na.color parameter
https://gist.github.com/lopspower/03fb1cc0ac9f32ef38f4
So just add FF in front for a full transparent layer
factpal <- colorFactor(topo.colors(4), nc$factor_col, na.color = "#FF000000")

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With