I would like to change the fill color of NA values in a choropleth r plotly interactive map from white (or transparent?) to light gray. This is for an R Shiny application, so I would like to retain the map interactivity features of plotly. I am using custom shapes using the sf package. Does anyone have a solution for this? Thank you.
I have a reproducible example here:
library(sf)
library(dplyr)
library(plotly)
nc <- sf::st_read(system.file("shape/nc.shp", package="sf"), quiet = TRUE) %>%
mutate(NA.AREA = ifelse(AREA > 0.15, NA, AREA))
plot_ly(nc,
split = ~NAME,
color = ~NA.AREA,
colors = 'Blues',
alpha = 1,
stroke = I("#000000"),
span = I(1),
hovertext = ~NAME,
hoverinfo = "text",
showlegend = FALSE)
Example r plotly choropleth map with NA values:
I see there is a way to do this in ggplot2, but I am not seeing any documentation on how to do this in plotly for R.
We can filter
the data for NA and non-NA values, and use add_sf
to plot them separately with desired colors:
library(sf)
library(dplyr)
library(plotly)
nc <- sf::st_read(system.file("shape/nc.shp", package="sf"), quiet = TRUE) %>%
mutate(NA.AREA = ifelse(AREA > 0.15, NA, AREA))
plot_ly() %>%
add_sf(data = nc %>% filter(!is.na(NA.AREA)),
split = ~NAME,
color = ~NA.AREA,
colors = 'Blues',
alpha = 1,
stroke = I("#000000"),
span = I(1),
hovertext = ~NAME,
hoverinfo = "text",
showlegend = FALSE) %>%
add_sf(data = nc %>% filter(is.na(NA.AREA)),
split = ~NAME,
color = I("grey"),
alpha = 1,
stroke = I("#000000"),
span = I(1),
hovertext = ~NAME,
hoverinfo = "text",
showlegend = FALSE)
Created on 2024-07-19 with reprex v2.0.2