[英]Leaflet Legend for Custom Markers in R
我有一个 R Shiny 应用程序,它使用 Leaflet 创建交互式地图。 在此地图上,分类变量用于指定不同种类的点,并使用自定义标记(不同图标,取决于因子级别)进行可视化。
我想要做的是在情节中添加一个图例,但让图例显示各种标记图标而不是纯色。 传奇教程不包括这一点。
我遇到了另一个似乎解决了这个问题的 SO 答案- 但它是用 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)
虽然目前在 addLegend() 中没有实现图标的使用,但 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/examples/custom-icons/leaf-green.png",
"http://leafletjs.com/examples/custom-icons/leaf-red.png"
),
iconWidth = 38, iconHeight = 95,
iconAnchorX = 22, iconAnchorY = 94)
html_legend <- "<img src='http://leafletjs.com/examples/custom-icons/leaf-green.png'>green<br/>
<img src='http://leafletjs.com/examples/custom-icons/leaf-red.png'>red"
# Produce Map:
leaflet(data = quakes) %>% addTiles() %>%
addMarkers(~long, ~lat, icon = leafIcons) %>%
addControl(html = html_legend, position = "bottomleft")
其中产生:
回应上面的评论:无论您定义的初始大小如何,您都可以更改图例中图标的大小。 您所要做的就是添加
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.