问题描述
我有一个R Shiny应用程序,该应用程序使用Leaflet创建交互式地图.在此地图上,分类变量用于指定不同种类的点,并使用自定义标记(不同的图标,具体取决于因子级别)可视化.
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.
我遇到了另一个这样的答案似乎可以解决这个问题-但是它是用JavaScript完成的,我不确定如何翻译/是否可以将其翻译成R语言.
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)
推荐答案
图标的使用是>在addLegend()中目前尚未实现,Yihui建议使用原始html来使用addControl()-效果很好!
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/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")
链接
- 绿色: http://leafletjs.com/examples/custom-icons /leaf-green.png
- 红色: http://leafletjs.com/examples/custom-icons /leaf-red.png
- 橙色: http://leafletjs.com/examples/custom-icons /leaf-orange.png
- Green: http://leafletjs.com/examples/custom-icons/leaf-green.png
- Red: http://leafletjs.com/examples/custom-icons/leaf-red.png
- Orange: http://leafletjs.com/examples/custom-icons/leaf-orange.png
Links
哪个会产生:
这篇关于R中自定义标记的传单图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!