R中自定义标记的传单图例 [英] Leaflet Legend for Custom Markers in R

查看:100
本文介绍了R中自定义标记的传单图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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")

链接

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆