用圆形小册子R创建图例

时间:2016-05-25 19:43:41

标签: r shiny leaflet legend

我试图创建一个带有由变量大小的点的传单地图。是否可以使用不同大小的圆圈创建表示不同变量值的图例?我发现另一篇文章展示了如何在图例中将方块转换为圆圈,但我不确定如何更改图例中不同圆圈的大小。

例如,这里是一个虚拟脚本,它创建了与2个变量类(5和10)相关联的10个点。我想要一个带有两个圆圈的图例,其大小与使用半径为5和10的addCircleMarkers指定的相同。如果有人可以修改以创建我想要的东西,我将非常感激!谢谢!

library(shiny)
library(leaflet)

#create data
Points<-data.frame(x=runif(10,20,21), y=runif(10,0,1), var=rep(c(5,10),5))
map = leaflet() %>% addTiles()

# Set up shiny app
shinyApp(ui=bootstrapPage(
tags$style(type = "text/css", "html, body {width:100%;height:100%}",
".leaflet .legend i{
border-radius: 50%;
width: 10px;
height: 10px;
margin-top: 4px;
}
"
),
leafletOutput("myMap", width = "100%", height = "100%")),

server= function(input, output){

output$myMap = renderLeaflet({map %>% 
    addCircleMarkers(Points$x,Points$y,radius=Points$var) %>%
    addLegend(colors=rep("blue",2), labels=c(5,10))
  })
})

1 个答案:

答案 0 :(得分:13)

你很幸运。仔细查看leaflet.js会显示您在addLegend命令中添加的配置将用于创建图例项:

  

来自leaflet.js的第1083 - 1086行:

for (var i = 0; i < colors.length; i++) {
  legendHTML += '<i style="background:' + colors[i] + ';opacity:' +
                options.opacity + '"></i> ' + labels[i] + '<br/>';
}

这样,我们可以潜入一些额外的造型。在colors争论中,我们添加了一些widthheight来更改i标记(=图例圈)的大小。并且(这是可选的)我们可以使用labels div修改对齐样式,因为如果圆圈变大,它们往往会卡在线的顶部。

我冒昧地为您创建了一个自定义图例功能。这会为圆形大小带来额外的值。 (对于这一个应用程序来说,这是一个非常小的功能。)然后它添加了我上面提到的样式,而不需要担心拼写错误或其他错误。请注意,标准尺寸为10.

以下代码。玩得开心!如果有任何错误或错误,请写。我无法测试每种可能的情况。

library(shiny)
library(leaflet)

#create data
Points<-data.frame(x=runif(10,20,21), y=runif(10,0,1), var=rep(c(5,10),5))
map = leaflet() %>% addTiles()

# Set up shiny app
shinyApp(
  ui = bootstrapPage(
    tags$style(type = "text/css", "html, body {width:100%;height:100%}",
      ".leaflet .legend i{
      border-radius: 50%;
      width: 10px;
      height: 10px;
      margin-top: 4px;
      }
    "),
    leafletOutput("myMap", width = "100%", height = "100%")
  ),

  server = function(input, output){
    addLegendCustom <- function(map, colors, labels, sizes, opacity = 0.5){
      colorAdditions <- paste0(colors, "; width:", sizes, "px; height:", sizes, "px")
      labelAdditions <- paste0("<div style='display: inline-block;height: ", sizes, "px;margin-top: 4px;line-height: ", sizes, "px;'>", labels, "</div>")

      return(addLegend(map, colors = colorAdditions, labels = labelAdditions, opacity = opacity))
    }

    output$myMap = renderLeaflet({map %>% 
      addCircleMarkers(Points$x,Points$y,radius=Points$var) %>%
      addLegendCustom(colors = c("blue", "blue", "red"), labels = c("A", "B", "C"), sizes = c(10, 20, 40))
    })
  }
)