2016-06-16 53 views
8

我有一个R Shiny应用程序,它使用Leaflet创建交互式地图。在此地图上,分类变量用于指定不同类型的点,并使用自定义标记(不同的图标,根据因子级别)进行可视化。传单R中的自定义标记传说

我想要做的是添加一个图例的情节,但有图例显示各种标记图标,而不是纯色。 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

如果它的工作原理,最简单的方法可能只是到源的JavaScript。 – alistaire

回答

4

虽然使用的图标是addLegend()not currently implemented,艺辉建议使用的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") 

主要生产:

Leaflet Map with Categorical Legend

+0

试过这个,它可以工作,但图例中的图标非常大。有没有办法在html_legend代码或addControl()中调整它们的大小? – wraymond

+0

是的,图标大小是在icons()调用中定义的,在上面它们被设置为38px宽和95px高。 –

2

响应上面的注释:你可以改变的传奇图标的大小,无论你定义的初始大小。您所要做的就是将

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