Twitch_City Twitch_City - 3 months ago 55
R Question

Leaflet Legend for Custom Markers in R

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

What I would like to do is add a legend to the plot, but have the legend show the various marker icons instead of solid colours. The legends tutorial does not cover this.

I have come across another SO answer that seems to solve this - but it was done in JavaScript and I'm not sure how to translate it/if it can be translated to work in R. Anyone know how to accomplish this?

A 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)

Answer

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

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")

Which produces:

Leaflet Map with Categorical Legend