这是一个解决方案:
library(leaflet)
library(shiny)
library(ggplot2)
# example data frame
wxstn_df <- data.frame(Site = c("a", "a", "b"), Latitude = c(44.1, 44.1, 37), Longitude = c(-110.2, -110.2, -112.7), Month = c(1,2,1), Temp_avg = c(10, 18, 12))
ui <- fluidPage(column(7, leafletOutput("wsmap", height = "600px")),
column(5, plotOutput("plot", height = "600px"))
)
server <- function(input, output) {
## leaflet map
output$wsmap <- renderLeaflet({
leaflet() %>%
addTiles() %>%
addCircleMarkers(data = wxstn_df, ~unique(Longitude), ~unique(Latitude), layerId = ~unique(Site), popup = ~unique(Site))
})
# generate data in reactive
ggplot_data <- reactive({
site <- input$wsmap_marker_click$id
wxstn_df[wxstn_df$Site %in% site,]
})
output$plot <- renderPlot({
ggplot(data = ggplot_data(), aes(Month, Temp_avg)) +
geom_line()
})
}
shinyApp(ui, server)
主要问题是您没有更改您正在使用的示例中的对象名称,例如输入$wsmap_marker_click,因为wsmap是你传单ID的名称。同样,要访问站点信息,请使用 input$wsmap_marker_click$id 而不是 input$wsmap_marker_click$Site。在反应函数中打印对象通常很有用,可以探索输入对象的外观以及如何访问它的各个部分。
e.g.
# generate data in reactive
ggplot_data <- reactive({
print(input$wsmap_marker_click)
site <- input$wsmap_marker_click$id
print(site)
data <- wxstn_df[wxstn_df$Site %in% site,]
print(data)
data})
就我个人而言,在这种情况下,我更愿意使用反应式表达式从标记单击生成 ggplot 数据 (ggplot_data()),而不是创建reactiveValues 对象。每次单击标记时,绘图都会使用新的 ggplot_data() 进行更新。
并证明它有效: