Legend for custom markers in R

I have an R Shiny app that uses a Leaflet to create an interactive map. On this map, a categorical variable is used to indicate different types of points and is visualized using custom markers (different icons, depending on the level of the factor).

What I would like to do is add a legend to the plot, but the legend shows different marker icons instead of solid colors. the legend book does not apply to this.

I came across another SO answer that seems to have solved this , but it was done in JavaScript, and I'm not sure how to translate it / if it is possible to be translated to work in R. Does anyone know how to do this?

Basic reproducible example:

library(leaflet) # Sample Data data(quakes) quakes <- quakes[1:10,] # Choose Icon: leafIcons <- icons( iconUrl = ifelse(quakes$mag < 4.6, "http://leafletjs.com/docs/images/leaf-green.png", "http://leafletjs.com/docs/images/leaf-red.png" ), iconWidth = 38, iconHeight = 95, iconAnchorX = 22, iconAnchorY = 94) # Produce Map: leaflet(data = quakes) %>% addTiles() %>% addMarkers(~long, ~lat, icon = leafIcons) 
+8
r legend leaflet
source share
2 answers

While the use of icons is not currently implemented in addLegend (), Yihui suggested using addControl () using raw html - which works great!

 library(leaflet) # Sample Data data(quakes) quakes <- quakes[1:10,] # Choose Icon: leafIcons <- icons( iconUrl = ifelse(quakes$mag < 4.6, "http://leafletjs.com/docs/images/leaf-green.png", "http://leafletjs.com/docs/images/leaf-red.png" ), iconWidth = 38, iconHeight = 95, iconAnchorX = 22, iconAnchorY = 94) html_legend <- "<img src='http://leafletjs.com/docs/images/leaf-green.png'>green<br/> <img src='http://leafletjs.com/docs/images/leaf-red.png'>red" # Produce Map: leaflet(data = quakes) %>% addTiles() %>% addMarkers(~long, ~lat, icon = leafIcons) %>% addControl(html = html_legend, position = "bottomleft") 

What produces:

Categorical legend sheet map

+4
source share

Responding to the comment above: you can resize the icons in the legend, no matter what size you define. All you have to do is add

style='width:(desired_width)px;height:(desired_height)px'; to the HTML part.

In particular, your code would like to:

 library(leaflet) # Sample Data data(quakes) quakes <- quakes[1:10,] # Choose Icon: leafIcons <- icons( iconUrl = ifelse(quakes$mag < 4.6, "http://leafletjs.com/docs/images/leaf-green.png", "http://leafletjs.com/docs/images/leaf-red.png" ), iconWidth = 38, iconHeight = 95, iconAnchorX = 22, iconAnchorY = 94) html_legend <- "<img src='http://leafletjs.com/docs/images/leaf-green.png' style='width:10px;height:10px;'>green<br/> <img src='http://leafletjs.com/docs/images/leaf-red.png' style='width:10px;height:10px;'>red" # Produce Map: leaflet(data = quakes) %>% addTiles() %>% addMarkers(~long, ~lat, icon = leafIcons) %>% addControl(html = html_legend, position = "bottomleft") 
+2
source share

All Articles