Reputation: 625
Is there a mechanism for adding legends for for polygon outlines? I can map hollow polygon outlines by altering the color field and specifying fillOpacity=0 in my addPolygons() call, however I can achieve the same functionality when I addLegend() to the map? Example of hollow polygons and filled legend below:
library(sf)
library(leaflet)
library(tidyverse)
demo(nc, ask = FALSE, echo = FALSE)
nc_pal <- colorFactor(palette = "inferno", domain = nc$Name)
nc <- st_transform(nc, 4326)
leaflet(nc) %>%
addProviderTiles(provider = c("Esri.WorldTopoMap"),
group = "Esri.WorldTopoMap") %>%
addPolygons(
data = nc,
group = "nc",
color = ~ nc_pal(NAME),
fillOpacity = 0
) %>%
addLegend(
data = nc,
group = "nc",
colors = ~ nc_pal(NAME),
labels = ~ NAME
)
Upvotes: 1
Views: 554
Reputation: 41225
You could use the function from this question which creates a custom legend by making the inner filled squares white. Here is some reproducible code:
library(sf)
library(leaflet)
library(tidyverse)
leaflet(nc) %>%
addProviderTiles(provider = c("Esri.WorldTopoMap"),
group = "Esri.WorldTopoMap") %>%
addPolygons(
data = nc,
group = "nc",
color = ~ nc_pal(NAME),
fillOpacity = 0
) %>%
addLegendCustom(colors = rep("white", n = length(nc)),
labels = nc$NAME,
sizes = 20,
shapes = "square",
borders = nc_pal(nc$NAME))
The function from the question used:
addLegendCustom <- function(map, colors, labels, sizes, shapes, borders, opacity = 0.5){
make_shapes <- function(colors, sizes, borders, shapes) {
shapes <- gsub("circle", "50%", shapes)
shapes <- gsub("square", "0%", shapes)
paste0(colors, "; width:", sizes, "px; height:", sizes, "px; border:3px solid ", borders, "; border-radius:", shapes)
}
make_labels <- function(sizes, labels) {
paste0("<div style='display: inline-block;height: ",
sizes, "px;margin-top: 4px;line-height: ",
sizes, "px;'>", labels, "</div>")
}
legend_colors <- make_shapes(colors, sizes, borders, shapes)
# I added my modification here, see below
legend_labels <- make_labels(sizes, labels)
return(addLegend(map, colors = legend_colors, labels = legend_labels, opacity = opacity))
}
Created on 2023-08-15 with reprex v2.0.2
Upvotes: 1