Please help ! This question is very similar to this one that has been answered quite some time ago. However, I still cannot get my head around the solution:
How to create a chloropleth map in R Plotly based on a Categorical variable?
I'm trying to create an interactive Choropleth map in R for my shiny app based on categorical data, using plotly and sf data get from GADM. Here is a reproducible example:
library(raster)
library(tidyverse)
library(plotly)
library(sf)
# Get the map data in sf format
map_data <- getData("GADM", country = "FRA", level = 2, type = "sf")
# Transform sf data to modern crs object to avoid further warning message
st_crs(map_data) <- st_crs(map_data)
# Generate some random data for each region
department <- map %>% as.data.frame() %>% .[, 13]
set.seed(10, sample.kind="Rounding")
data <- sample(x = 0:1200, size = length(department), replace = T)
map_dat <- data.frame(department = department,
data = data)
# Assign Class as categories
map_dat <- map_dat %>%
mutate(Class = cut(data,
breaks = c(-Inf, 50, 100, 200, 500, 1000, Inf),
labels = c("< 50", "50 - 100", "100 - 200",
"200 - 500", "500 - 1000", "> 1000")))
# Join data and plot
plot_dat <- map %>% as.data.frame() %>%
left_join(map_dat, by = c("HASC_2" = "department")) %>%
st_as_sf()
plot_ly(plot_dat) %>%
add_sf(type = "scatter",
stroke = I("transparent"),
span = I(1),
alpha = 1,
split = ~NAME_2,
color = ~Class,
colors = "Reds",
text = ~paste0(NAME_2, "\n", data),
hoveron = "fills",
hoverinfo = "text") %>%
config(displayModeBar = F)
The problem that I have with the default legend is that it's too detail and cumbersome in some way, as I just want to display a small and compact box filled with categorical class that I assign, similar to the one in ggplot. I've try to split the map with categorical Class and the legend looks a little bit better, however my hover text does not work anymore, and still, I have no idea how to edit or change the style of the legend in order for it to look decent and neat, like to change the key symbols to become a circle or a square like we usually see in a legend map box.
plot_dat %>% plot_ly() %>%
add_sf(type = "scatter",
stroke = I("transparent"),
span = I(1),
alpha = 1,
split = ~Class,
color = ~Class,
colors = "Reds",
text = ~paste0(NAME_1, "\n", Count),
hoveron = "fills",
hoverinfo = "text") %>%
config(displayModeBar = F) %>%
layout(showlegend = F)
I've read through the documentation for plotly's Choropleth map in R and yet found no documentaion for categorical case (unlike Python). As I'm running out of options, my question is, is there any way to achive my desired goal here ? How can I create a proper legend box, or a bar for categorical data ?
Apologies if my question is not that clear. I'm eager to answer any questions if anyone has. Thank you in advance.

