#r #shiny #leaflet
Вопрос:
Я создал карту странствий морских млекопитающих, чтобы реагировать при изменении диапазона дат и выборе различных видов. Код «работает», но функция карты не отвечает должным образом, когда изменяется диапазон дат ввода слайдера.Круги на карте не отвечают. Я был бы признателен за любой совет, потому что я в растерянности после поиска и просмотра многих других подобных кодов.
Приложение.r
rm(list=ls()) #Libraries library(shiny) library(base) library(tidyverse) library(shinythemes) library(dplyr) library(ggmap) library(maps) library(mapdata) library(leaflet) library(leaflet.extras) library(glue) library(DT) library(lubridate) wdir=setwd(getwd()) options(shiny.reactlog = TRUE) source("~/scs-docker/rserver/scripts-habs/HAB_Bulletin/Stranding_Data/Stranding_Data/Map_function.R") #Read in Stranding Data Stranding_Data = read_csv("~/scs-docker/rserver/scripts-habs/HAB_Bulletin/Stranding_Data/Stranding_Data/All_Strandings_2019-2021.csv") #Clean up stranding data Stranding_Data2 = Stranding_Data %gt;% drop_na(Strand_Date) %gt;% #remove lines with no data drop_na(Common_Name) %gt;% #remove sea birds filter(Common_Name != "Pacific loon", Common_Name != "Brandts cormorant", Common_Name != "Double-crested cormorant", Common_Name != "Western Grebe", Common_Name != "Common Loon", Common_Name != "Black-Vented Shearwater") %gt;% select(Program,Strand_Date,Common_Name,Scientific_Name,Age_Class,Sex,Stranding_County,Stranding_City, Latitude,Longitude) endDate = as.Date(max(Stranding_Data2$Strand_Date)) startDate = endDate - 30 minDate = as.Date(min(Stranding_Data2$Strand_Date)) # Define UI for application ui lt;- fluidPage( #fillPage theme = shinytheme("cerulean"), # Application title titlePanel("Suspect Domoic Acid Marine Mammal Strandings", windowTitle = "SCCOOS"), # Sidebar with a slider input for number of bins sidebarLayout( sidebarPanel( sliderInput(inputId = "Strand_Date", label = "Stranding Date", width = '100%', min = minDate, max = endDate, value = c(startDate, endDate)), # selectInput( # inputId = "Program", # label = "Stranding Center", # choices = list("The Marine Mammal Center" = "TMMC", # "Channel Islands Marine Wildlife Institute" = "CIMWI", # "California Wildlife Center" = "CWC", # "Marine Animal Rescue" = "MAR", # "Marine Mammal Care Center Los Angeles" = "MMCC-LA", # "Pacific Marine Mammal Center"= "PMMC", # "SeaWorld San Diego"= "SeaWorld")), selectInput( #selectInput checkboxGroupInput inputId = "Common_Name", label= "Species", choices=sort(unique(Stranding_Data2$Common_Name)), multiple = T, selected = "California Sea Lion"), h6("Disclaimer: These are suspected marine mammal strandings due to domoic acid (DA) toxicosis. Species exposed to DA often result in seizures, epilepsy, cardiomyopathy, and death depending upon the ingested dose. Neuroscopy are required to confirm cases of DA toxicosis.", align = "left") ), # Show a map of the generated distribution and table of data mainPanel( tabsetPanel( type = "tabs", tabPanel("Map", leafletOutput(outputId = "mymap", height = 600)), #height = "1000px", width = "100%" #height=1000 tabPanel("Table",DT::dataTableOutput("mytable", height = 600)) ) ) ) ) server lt;- function(input, output, session) { #create map output$mymap lt;- renderLeaflet({ #leaflet function to create the basemap Stranding_Map(Stranding_Data2) }) observe({ #leafletproxy function for circles Add_Circles(Stranding_Data2, group=input$Common_Name, daterange = input$Strand_Date) }) #create table output$mytable = DT::renderDataTable({ daterange = input$Strand_Date endDate = daterange[2] startDate = daterange[1] Stranding_Data2 %gt;% filter(Common_Name %in% input$Common_Name, Strand_Dategt;=startDate amp; Strand_Datelt;=endDate) datatable(Stranding_Data2) }) } # Run the application shinyApp(ui = ui, server = server)
Функция Привязки Карты
Stranding_Map = function(data){ species_name = c("California Sea Lion", "Northern Fur Seal", "Guadalupe Fur Seal", "Common Bottlenose Dolphin", "Short-Beaked Common Dolphin", "Striped dolphin", "North Pacific Right Whale", "Gray Whale") my_palette = c("#FF0000FF", "#FFBF00FF", "#80FF00FF", "#00FF40FF", "#00FFFFFF", "#0040FFFF", "#8000FFFF", "#FF00BFFF") #previewColors(colorFactor(my_palette, levels = species_Name), species_Name) factpal = colorFactor(palette=my_palette, domain=species_name) leaflet() %gt;% addProviderTiles(providers$Esri.OceanBasemap) %gt;% setView(lng = -122, lat = 38, zoom = 5) %gt;% addLegend( pal= factpal, values = species_name, opacity = 1, position = "topright", title="Species Name", layerId = "color-legend") } Add_Circles = function(data, group, daterange){ endDate = daterange[2] startDate = daterange[1] data = data %gt;% filter(Common_Name %in% group, Strand_Dategt;=startDate amp; Strand_Datelt;=endDate) Common_Name = c("California Sea Lion", "Northern Fur Seal","Guadalupe Fur Seal", "Common Bottlenose Dolphin","Short-Beaked Common Dolphin","Striped dolphin", "North Pacific Right Whale","Gray Whale") my_palette = c("#FF0000FF", "#FFBF00FF", "#80FF00FF", "#00FF40FF", "#00FFFFFF", "#0040FFFF", "#8000FFFF", "#FF00BFFF") factpal2 = colorFactor(palette=my_palette, levels=Common_Name) leafletProxy("mymap") %gt;% addCircleMarkers(data=data, color= ~factpal2(Common_Name), fillOpacity = 1, weight = 0.5, stroke= 'none', label=paste( data$Strand_Date,",", "Rehab Center:",data$Program,",", data$Common_Name,""), #"County:",data$Stranding_County,",", #"City:",data$Stranding_City,""), popup=paste( "Stranding Date:",data$Strand_Date,"lt;brgt;", "Rehab Center:", data$Program,"lt;brgt;", "Species:", data$Common_Name,"lt;brgt;", "County:", data$Stranding_County,"lt;brgt;", "City:", data$Stranding_City,"lt;brgt;"), lng=~Longitude, lat=~Latitude) }
Комментарии:
1. Я был бы заинтересован в помощи, если это возможно, но я не могу запустить код, который у вас есть, потому что у меня нет вашего csv. Не могли бы вы опубликовать часть своих данных или, может быть, просто создать поддельный фрейм данных, который показывает проблему, чтобы другие могли ее проверить? Спасибо!
2. У вас есть
Stranding_Data2 %gt;% filter...
то, что не сохраняет результат после фильтрации… ты это имел в видуStranding_Data2 lt;- Stranding_Data2 %gt;% filter...
?
Ответ №1:
Исправлена моя ошибка, обновив функцию моего сервера! Спасибо за совет!
server lt;- function(input, output, session) { #create map output$mymap lt;- renderLeaflet({ #leaflet function to create the basemap daterange = input$Strand_Date endDate = daterange[2] startDate = daterange[1] print(startDate) print(input$endDate) print(input$Common_name) x = Stranding_Data2 %gt;% filter(Common_Name %in% input$Common_Name, Strand_Dategt;=startDate amp; Strand_Datelt;=endDate) Stranding_Map(x) }) observe({ #leafletproxy function for circles Add_Circles(Stranding_Data2, group=input$Common_Name, daterange = input$Strand_Date) }) #create table output$mytable = DT::renderDataTable({ daterange = input$Strand_Date endDate = daterange[2] startDate = daterange[1] print(startDate) print(input$endDate) print(input$Common_name) x = Stranding_Data2 %gt;% filter(Common_Name %in% input$Common_Name, Strand_Dategt;=startDate amp; Strand_Datelt;=endDate) }) }