简体   繁体   中英

Updating spatial polygon dataframe with shiny

My shapefile has columns mean , median and sd and i want to draw a choropleth map in R Shiny. I have a sidebar that controls if tiles of map should display mean , median or sd . But I am not able to do it in Shiny. I tried using the reactive funtions but I keep getting the error below

Error: Polygon data not found; please provide addPolygons with data and/or lng/lat arguments

My code is below

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

val <- readOGR('exampleshapefile.shp')
mybins <- c(24,270,470,555,770,2000,Inf)

ui <- fluidPage(
  sidebarLayout(
    
    sidebarPanel(
      radioButtons("stat", "Stat Type:",
                   c("Mean" = "mean",
                     "Median" = "q0_50",
                     "Standard Deviation" = "sd"
                   )
      )
      
    ),
    mainPanel("mainpanel",
              leafletOutput("distSAM")
              
    )
  )
)

server <- function(input, output) {
  
  ###################### dist-wise
  data <- eventReactive(input$stat,{
    val@data$input$stat
  })
  
  pal <- reactive({
    colorBin(palette="RdYlGn", domain = data(), na.color = "transparent", bins=mybins, reverse = TRUE)
  })
  
  labels <- reactive({
    sprintf(
      "<strong>%s<br/>%s</strong>%.1f",
      val@data[["NAME_2"]], "SAM: ", data()
    ) %>% lapply(htmltools::HTML)
  })
  
  output$distSAM <- renderLeaflet({
    df <- data()
    pal <- pal()
    lab <- labels()
    
    leaflet()  %>% addTiles() %>%
      addPolygons(data = df,
                  fillColor = ~pal(mean),
                  weight = 2,
                  opacity = 1,
                  color = "white",
                  dashArray = "3",
                  fillOpacity = 0.7,
                  highlight = highlightOptions(
                    weight = 5,
                    color = "#666",
                    dashArray = "",
                    fillOpacity = 0.7,
                    bringToFront = TRUE),
                  label = lab,
                  labelOptions = labelOptions(
                    style = list("font-weight" = "normal", padding = "3px 8px"),
                    textsize = "15px",
                    direction = "auto")) %>%
      addLegend(pal = pal, values = ~df$mean,
                title = "SAM </br> Prevalence",
                position = "bottomleft")
    
  }
  )
}

shinyApp(ui, server)

val@data$input$stat is not a valid data selection. Instead you can use:

selected_stat <- val[[input$stat]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM