-->

R shiny checkboxGroup to plot data on map

2019-08-29 13:33发布

问题:


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