R 中的 Shiny 和 Leaflet 无需重绘即可更新多边形

MJC*_*MJC 5 r leaflet shiny

我希望能够在不再次绘制多边形的情况下更新传单中绘制多边形的属性。这使它变得相当慢,而且由于我想将它用于时间序列,因此它们需要快速更新。我添加了一些示例代码,其中按钮更新(多边形的)颜色,但是由于重绘,它很慢。任何建议将是非常受欢迎的!我重用了之前问题的一些元素来获得一个下载自己的 shapefile 的工作示例。期待您的解决方案!

# bits of code from: /sf/ask/2038264161/

library(rgdal)
library(leaflet)
library(shiny)

download.file(file.path('http://www.naturalearthdata.com/http/',
                        'www.naturalearthdata.com/download/50m/cultural',
                        'ne_50m_admin_0_countries.zip'), 
              f <- tempfile())
unzip(f, exdir=tempdir())

world <- readOGR(tempdir(), 'ne_50m_admin_0_countries', encoding='UTF-8')

#lets grab 20 countries:
commonwealth <- c("Antigua and Barb.", "Australia", "Bahamas", "Bangladesh", 
                  "Barbados", "Belize", "Botswana", "Brunei", "Cameroon", "Canada", "Cyprus",
                  "Dominica", "Fiji", "Ghana", "Grenada", "Guyana", "India", "Jamaica", "Kenya",
                  "Kiribati")
col<-c("red","green", "yellow","blue")


ui <- fluidPage(
  leafletOutput("mymap"),
  p(),
  actionButton("recolor", "New colors")
)

server <- function(input, output, session) {

  points <- eventReactive(input$recolor, {
    sample(col, 20, replace=TRUE)
  }, ignoreNULL = FALSE)

  output$mymap <- renderLeaflet({
    leaflet() %>%
      addProviderTiles(providers$Stamen.TonerLite,
                       options = providerTileOptions(noWrap = TRUE)
      ) %>%
      addPolygons(data=subset(world, NAME %in% commonwealth), weight=2, color=~sample(col, 20, replace=TRUE))
  })

  observe({
    leafletProxy("mymap", data = points()) %>%
    clearShapes() %>%
      addPolygons(data=subset(world, NAME %in% commonwealth), weight=2, color=~points())
  })
}

shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)