Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

leaflet

r-sf

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

like image 460
TDP Avatar asked Jan 21 '26 08:01

TDP


2 Answers

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))
like image 157
astrofunkswag Avatar answered Jan 24 '26 08:01

astrofunkswag


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")

enter image description here

like image 29
carverd Avatar answered Jan 24 '26 07:01

carverd



Donate For Us

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