gpt4 book ai didi

r - 用圆圈传单 R 创建图例

转载 作者:行者123 更新时间:2023-12-02 03:30:38 24 4
gpt4 key购买 nike

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

例如,下面是一个虚拟脚本,它创建与 2 个变量类别(5 和 10)关联的 10 个点。我想要一个带有两个圆圈的图例,其大小与 addCircleMarkers 指定的圆圈大小相同,半径分别为 5 和 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){

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

最佳答案

你很幸运。仔细查看 leaflet.js 会发现,您在 addLegend 命令中添加的配置实际上用于创建图例项:

Lines 1083 - 1086 from leaflet.js:

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

关于r - 用圆圈传单 R 创建图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37446283/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com