在R小册子中使用菱形,三角形和星形

时间:2016-12-29 01:51:09

标签: r leaflet

我有不同类型的观察,我想用不同的形状和颜色在宣传单上展示它们。在R中的小册子中是否可以使用菱形,三角形,星形和其他形状?

我提供了虚拟数据,并创建了不同颜色的圆形标记。

library(leaflet)

 lat1= 36+runif(n=5,min=-1,max=1)
 lon1 =-115+runif(n=5,min=-1,max=1)

 lat2= 35+runif(n=5,min=-0.5,max=0.5)
 lon2 =-110+runif(n=5,min=-0.5,max=0.5)

 lat3= 34+runif(n=5,min=-0.5,max=0.5)
 lon3 =-112+runif(n=5,min=-0.5,max=0.5)

 data_all=rbind(data.frame(Longitude=lon1,Latitude=lat1,Group=1),
           data.frame(Longitude=lon2,Latitude=lat2,Group=2),
           data.frame(Longitude=lon3,Latitude=lat3,Group=3))

 pal <- colorFactor(c("red","blue","purple"), domain = c(1,2,3))


 leaflet(data_all) %>% addTiles() %>%
   addCircleMarkers(~Longitude, ~Latitude,popup=~paste0("Group=  ",data_all$Group),
     radius = 10,
    color = ~pal(Group),
    stroke = FALSE, fillOpacity = 1
     )

enter image description here

1 个答案:

答案 0 :(得分:2)

这是使用基础R绘图符号的解决方案。基本上,您创建了一系列具有所需形状的临时png文件,然后根据该组使用该文件来表示您的数据。

library(leaflet)

# this is modified from 
# https://github.com/rstudio/leaflet/blob/master/inst/examples/icons.R#L24
pchIcons = function(pch = 1, width = 30, height = 30, bg = "transparent", col = "black", ...) {
  n = length(pch)
  files = character(n)
  # create a sequence of png images
  for (i in seq_len(n)) {
    f = tempfile(fileext = '.png')
    png(f, width = width, height = height, bg = bg)
    par(mar = c(0, 0, 0, 0))
    plot.new()
    points(.5, .5, pch = pch[i], col = col[i], cex = min(width, height) / 8, ...)
    dev.off()
    files[i] = f
  }
  files
}

lat1= 36+runif(n=5,min=-1,max=1)
lon1 =-115+runif(n=5,min=-1,max=1)

lat2= 35+runif(n=5,min=-0.5,max=0.5)
lon2 =-110+runif(n=5,min=-0.5,max=0.5)

lat3= 34+runif(n=5,min=-0.5,max=0.5)
lon3 =-112+runif(n=5,min=-0.5,max=0.5)

data_all=rbind(data.frame(Longitude=lon1,Latitude=lat1,Group=1),
               data.frame(Longitude=lon2,Latitude=lat2,Group=2),
               data.frame(Longitude=lon3,Latitude=lat3,Group=3))

shapes = c(5, 6, 8) # base R plotting symbols (http://www.statmethods.net/advgraphs/parameters.html)
iconFiles = pchIcons(shapes, 40, 40, col = c("red", "blue", "purple"), lwd = 4)


leaflet(data_all) %>% addTiles() %>%
  addMarkers(
    data = data_all,
    icon = ~ icons(
      iconUrl = iconFiles[Group],
      popupAnchorX = 20, popupAnchorY = 0
    ),
    popup=~paste0("Group=  ",data_all$Group)
  )

显然,您可以在addMarkers中使用其他png文件。 此解决方案基于https://github.com/rstudio/leaflet/blob/master/inst/examples/icons.R#L24

中相当隐蔽的示例