【问题标题】:R Shiny Leaflet - clearShapes() not working?R Shiny Leaflet - clearShapes() 不起作用?
【发布时间】:2015-07-17 17:13:39
【问题描述】:

我有一个格式如下的数据集 (tst_geo.csv):

lat, lon, time
10, 20, 1
10, 20, 2
10, 20, 3
40, 40, 4
40, 40, 5
40, 40, 6
0, 0, 7
0, 0, 8
0, 0, 9

R 代码:

library(shiny)
library(leaflet)
library(plyr)

ui <- fluidPage(
    sidebarLayout(

        sidebarPanel(
            uiOutput("slider")
        ),
        mainPanel(
            leafletOutput("map")
        )
    )
)

server <- function(input, output, session){

    df <- read.csv("tst_geo.csv", header=TRUE)
    df['time'] <- as.numeric(df$time)

    #make dynamic slider
    output$slider <- renderUI({
        sliderInput("time_span", "Time Span", step=1, min=min(df$time), 
                    max=max(df$time), value = c(min(df$time), max(df$time)))
    })

    filter_df <- reactive({
        df[df$time >= input$time_span[1] & df$time <= input$time_span[2], ]
    })

    output$map <- renderLeaflet(
        leaflet() %>% addTiles()
    )

    observe({
        points_df <- ddply(filter_df(), c("lat", "lon"), summarise, count = length(timestamp))
        cat(nrow(points_df))
        leafletProxy("map", data = points_df) %>% clearShapes() %>% addCircles()
    })

}

shinyApp(ui, server)

我有一个滑块,只显示特定时间范围内的点。

但是,在observe 函数内部,当我调用clearShapes() 时,这些点并没有被清除。

任何想法为什么会发生这种情况?

【问题讨论】:

    标签: r shiny leaflet plyr


    【解决方案1】:

    在这种情况下,罪魁祸首是renderUI()。因为你使用了renderUI(),所以滑块的渲染延迟了。当观察者第一次运行时,滑块还没有出现,input$time_span 最初是NULL,所以filter_df() 返回一个空数据框。在这种情况下,我没有看到使用renderUI() 的特殊原因(也许你有一个原因),你可以将sliderInput() 移动到ui.R,或者在向地图添加圆圈之前检查if (is.null(input$time_span)) ,或将observe() 更改为observeEvent()(如果您使用的是最新版本的shiny):

    observeEvent(input$time_span, {
        points_df <- ddply(filter_df(), c("lat", "lon"), summarise, count = length(timestamp))
        cat(nrow(points_df))
        leafletProxy("map", data = points_df) %>% clearShapes() %>% addCircles()
    })
    

    【讨论】:

      猜你喜欢
      • 2017-05-10
      • 2017-08-20
      • 2020-07-08
      • 2020-09-29
      • 1970-01-01
      • 2017-11-17
      • 2017-04-21
      • 2020-04-26
      相关资源
      最近更新 更多