gpt4 book ai didi

r - 是否可以在不重新创建 map 对象的情况下更新传单中的多边形填充以使其 Shiny

转载 作者:行者123 更新时间:2023-12-03 22:45:05 24 4
gpt4 key购买 nike

在传单中,我通常会创建一个 map :

server.R

shinyServer(function(input, output, session) {
url <- "custommapboxurl"
attrib <- "Maps by http://www.mapbox.com/Mapbox"

...
map_out <- reactive({

map <- leaflet()%>%
addTiles(urlTemplate = url, attribution = HTML(attrib))%>%
addPolygons(data = sub_shape,
fill = TRUE,
fillColor = colors$color,
fillOpacity = .8,
stroke = TRUE,
weight = 3,
color = "white",
dashArray = c(5,5),
popup = pops
)
})

output$myMap <- renderLeaflet({
map_out()
})
...
})
sub_shape上面是我的 shapefile(在这种情况下,是美国的邮政编码),而 colors$color 是对应于每个形状的动态颜色向量。您可以使用此处的链接重新创建: http://www.nws.noaa.gov/geodata/catalog/national/html/province.htm , 和 colors <- data.frame(color = colorRampPalette(c("white","blue"))(13))
ui.R
shinyUI(
...
leafletOutput('myMap', width = "100%" , height = "100%")
...
)

这给出:

enter image description here

我想做的是根据用户的输入更改颜色向量。例如,他们可能会选择一个不同的变量来为每个邮政编码着色,从而生成一个新的渐变。

Shiny 允许我们这样做,就像我根据输入小部件更改颜色向量一样, react 函数会刷新,并基于新向量重新创建 map 。问题在于,对于大型 shapefile 对象,此刷新需要很长时间。

有没有办法直接改变当前渲染形状的颜色,而无需重新创建整个图层?似乎 color 参数被锁定在 Leaflet() 函数中。有没有其他方法可以得到它?

最佳答案

为了说明@Yihui Xie 的评论,这里是一个使用 leafletProxy 的例子。更改多边形的颜色,基于 selectInput .

library(shiny)
library(leaflet)
library(sp)
library(raster)

## Spatial Polygon ##########
Sr1 = Polygon(cbind(c(2,4,4,1,2),c(2,3,5,4,2)))
Sr2 = Polygon(cbind(c(5,4,2,5),c(2,3,2,2)))
Sr3 = Polygon(cbind(c(4,4,5,10,4),c(5,3,2,5,5)))
Sr4 = Polygon(cbind(c(5,6,6,5,5),c(4,4,3,3,4)), hole = TRUE)
Srs1 = Polygons(list(Sr1), "s1")
Srs2 = Polygons(list(Sr2), "s2")
Srs3 = Polygons(list(Sr3, Sr4), "s3/4")
SpP = SpatialPolygons(list(Srs1,Srs2,Srs3), 1:3)
SpPDF <- SpatialPolygonsDataFrame(SpP, data = data.frame(x=1:length(SpP)), match.ID = F)
Extent = extent(SpPDF)

## UI ##########
ui <- fluidPage(
selectInput("col", label = "Select a color", choices = c("Blues", "viridis", "magma")),
leafletOutput("map")
)

## SERVER ##########
server <- function(input, output) {
output$map <- renderLeaflet({
leaflet() %>%
addTiles() %>%
fitBounds(lng1 = Extent[1],lat1 = Extent[3], lng2 = Extent[2], lat2 = Extent[4])
})

observe({
req(input$col)
pal = colorFactor(input$col, domain = factor(SpPDF$x))
leafletProxy("map") %>%
addPolygons(data = SpPDF, color = ~pal(factor(SpPDF$x)))
})
}

shinyApp(ui, server)

关于r - 是否可以在不重新创建 map 对象的情况下更新传单中的多边形填充以使其 Shiny ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30091093/

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