我有一个R Shiny应用程序,它使用Leaflet创建交互式地图。在此地图上,分类变量用于指定不同类型的点,并使用自定义标记(不同的图标,取决于因子级别)进行可视化。
我想要做的是在图中添加一个图例,但让图例显示各种标记图标而不是纯色。 legends tutorial不包含此内容。
我遇到了另一个SO answer that seems to solve this - 但它是用JavaScript完成的,我不知道如何翻译它/如果它可以翻译成在R中工作。任何人都知道如何实现这一目标?
一个基本可重复的例子:
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)
答案 0 :(得分:6)
虽然在addLegend()中使用了图标not currently implemented,但是Yihui建议使用addControl(),使用原始的html - 这非常有效!
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")
产生:
答案 1 :(得分:3)
回应上述评论:无论您定义的初始尺寸如何,都可以更改图例中图标的大小。您所要做的就是添加
style='width:(desired_width)px;height:(desired_height)px';
到HTML部分。
具体来说,您的代码需要:
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")