R shiny checkboxGroup to plot data on map

荒凉一梦 提交于 2019-12-25 00:24:35

问题



I am very new to shiny, and I have a question.
I have a simple dataset with observations (Number_Total) of species (Species), in a certain location (X,Y).

I would like to generate a map, that enables you to select the species in a dropdown menu. Shiny then shows you were the species occurs on the map.

I got pretty far (for my experience), but selecting species in the menu does not do anything...

ui <- (fluidPage(titlePanel("Species Checker"),  
                 sidebarLayout(
                   sidebarPanel(
                      selectizeInput('species', 'Choose species', 
                   choices    = df$Species, multiple = TRUE)
                     ),
                   mainPanel(
                     leafletOutput("CountryMap", 
               width = 1000, height = 500))
                 )
))

The server side

server <- function(input, output, session){
  output$CountryMap <- renderLeaflet({
    leaflet() %>% addTiles() %>% 
      setView(lng = 10, lat = 40, zoom = 5) %>%
      addCircles(lng = df$Y, lat = df$X, weight = 10, 
      radius =sqrt(df$Number_Total)*15000, popup = df$Species)
  })


  observeEvent(input$species, {

    if(input$species != "")
    {
      leafletProxy("CountryMap") %>% clearShapes()
      index = which(df$Species == input$species)
      leafletProxy("CountryMap")%>% addCircles(lng = df$X[index], 
      lat = df$Y[index],
                                               weight = 1, 
     radius =sqrt(df$Number_Total[index])*30, popup = df$Species[index])
    }
  }) 

}

And finally plot it

shinyApp(ui = ui, server = server)

I know my code is probably messy, but again, I blaim my experience =) I did not manage to get an example dataset in here right away, so here it comes as picture

This is the result of the above code (with slightly different data) enter image description here


回答1:


Here's what you need. I think you are skilled enough to understand this but comment if you have any questions.

server <- function(input, output, session) {
  # map_data <- reactive({
    # req(input$species)
    # df[df$Species %in% input$species, ]
  # })

  output$CountryMap <- renderLeaflet({
    leaflet() %>% addTiles() %>% 
      setView(lng = 10, lat = 40, zoom = 5)
  })

  map_proxy <- leafletProxy("CountryMap")

  observe({
    md <- df[df$Species %in% input$species, ]
    map_proxy %>%
      addCircles(lng = md$Y, lat = md$X, weight = 10, 
      radius = sqrt(md$Number_Total)*15000, popup = md$Species)
  })
}


来源:https://stackoverflow.com/questions/53186213/r-shiny-checkboxgroup-to-plot-data-on-map

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!