Jan*_*ane 3 interactive r ggplot2 leaflet shiny
我正在R中使用Shiny,试图创建一个Leaflet贴图,该贴图允许用户单击任何标记以生成代表该特定位置的信息(温度)的对应图。
我结合了这个问题的代码(单击传单地图上的点作为闪亮的图的输入)和此博客的第二个技巧(https://www.r-bloggers.com/4-tricks-for-working-使用-r-leaflet-and-shiny /),但似乎仍无法在Shiny中成功注册单击的标记点。
即,当我单击任何站点时,没有内容。
根据进一步的研究,我找不到任何解决方案,不胜感激。
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) {
# create a reactive value to store the clicked site
stn <- reactiveValues(clickedMarker = NULL)
## leaflet map
output$wsmap <- renderLeaflet({
leaflet() %>%
addTiles() %>%
addCircleMarkers(data = wxstn_df, ~unique(Longitude), ~unique(Latitude), layerId = ~unique(Site), popup = ~unique(Site))
})
# store the click
observeEvent(input$map_marker_click, {
stn$clickedMarker <- input$map_marker_click
})
output$plot <- renderPlot({
ggplot(wxstn_df[wxstn_df$Site %in% stn$clickedmarker$Site,], aes(Month, Temp_avg)) +
geom_line()
})
}
shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)
这是一个解决方案:
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)
Run Code Online (Sandbox Code Playgroud)
主要问题是您没有从所使用的示例中更改对象名称,例如input $ wsmap_marker_click,因为wsmap是您的传单ID的名称。同样,要访问站点信息,请使用input $ wsmap_marker_click $ id,而不要输入$ wsmap_marker_click $ Site。在反应函数中打印对象通常很有用,以探索输入对象的外观以及如何访问其中的部分。
例如
# 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})
Run Code Online (Sandbox Code Playgroud)
就个人而言,在这种情况下,我宁愿使用反应式表达式通过单击标记来生成ggplot数据(ggplot_data()),而不是创建reactValues对象。每次单击标记时,图将使用新的ggplot_data()更新。
并证明它有效:
| 归档时间: |
|
| 查看次数: |
1072 次 |
| 最近记录: |