I created a leaflet map and now need to customize the order of the legend. By default leaflet
alphabetizes the legend order. In the example below, I need the legend order to be (from top to bottom): Charlottesville, Richmond, Charlotte, Raleigh. How can I customize the leaflet legend order?
Example:
# Import needed libraries
library(tidyverse)
library(leaflet)
# Create example dataset
aa <- data.frame(
city = c('Richmond','Charlottesville', 'Raleigh', 'Charlotte'),
lat = c(37.53,38.01,35.78,35.22),
lon = c(-77.44,-78.47,-78.63,-80.84))
# Create custom colors for markers
pal <- leaflet::colorFactor(c('springgreen', 'dodgerblue', 'red', 'purple'),
domain = c('Richmond','Charlottesville', 'Raleigh', 'Charlotte'),
ordered = TRUE)
# Make map
aa %>%
leaflet(options = leafletOptions(attributionControl = F,
zoomControl = F)) %>%
addTiles() %>%
addProviderTiles("Esri.WorldImagery") %>%
setView(-78.47,
36.53,
zoom = 7) %>%
addCircleMarkers(
lng = aa$lon,
lat = aa$lat,
label = aa$city,
fillColor = pal(aa$city),
fillOpacity = 1,
color = "black",
stroke = TRUE,
weight = 2,
radius = 5) %>%
addLegend('topright', pal = pal, values = aa$city, title = 'City', opacity = 1)
UPDATE:
Following the answer from the similar SO question linked above, I was able to reorder the legend however, now the legend colors do not match the marker color on the map.
For example, in the legend below Charlotte is red but on the map Charlotte is purple (i.e., the legend color for Charlotte should be purple). Need to be able to custom reorder the legend and keep the colors set appropriately.
# Create a new grouping variable
ord <- factor(aa$city, labels = c('Charlottesville', 'Richmond', 'Charlotte', 'Raleigh'))
# Create custom colors for markers
pal <- colorFactor(c('springgreen', 'dodgerblue', 'red', 'purple'),
levels = ord, ordered = TRUE)
# Make map
aa %>%
leaflet(options = leafletOptions(attributionControl = F,
zoomControl = F)) %>%
addTiles() %>%
addProviderTiles("Esri.WorldImagery") %>%
setView(-78.47,
36.53,
zoom = 7) %>%
addCircleMarkers(
lng = aa$lon,
lat = aa$lat,
label = aa$city,
fillColor = pal(ord),
fillOpacity = 1,
color = "black",
stroke = TRUE,
weight = 2,
radius = 5) %>%
addLegend('topright', pal = pal, values = ord, title = 'City', opacity = 1)
^ Legend colors do not match map colors (i.e. Charlotte is purple on map but red in legend).
You need to specify the levels
argument of factor
not the labels
argument:
ord <- factor(aa$city, levels = c('Charlottesville', 'Richmond', 'Charlotte', 'Raleigh'))
# Create custom colors for markers
pal <- colorFactor(c('springgreen', 'dodgerblue', 'red', 'purple'), levels = ord, ordered = TRUE)