【问题标题】:Preventing double call to brush reactive in shiny?防止在闪亮时双重调用刷反应?
【发布时间】:2021-12-22 09:38:08
【问题描述】:

我正在使用拉丝直方图来查询闪亮应用程序中的样本。在我的完整应用程序中,我覆盖了一个新的直方图,该直方图突出显示了选定的区域,并更新了一个显示过滤样本属性的 DT 数据表。

我注意到每次移动时都会调用两次依赖于画笔的反应。例如,每次刷直方图时,下面的 table_data 反应式会被调用两次。

app.R

library(ggplot2)
library(shiny)

df <- data.frame(x = rnorm(1000))
base_histogram <- ggplot(df, aes(x)) +
    geom_histogram(bins = 30)

# Define UI for application that draws a histogram
ui <- fluidPage(
    column(
      plotOutput("histogram", brush = brushOpts(direction = "x", id = "brush", delay=500, delayType = "debounce")),
      width = 6
    )
)

# Define server logic required to draw a histogram
server <- function(input, output) {
    output$histogram <- renderPlot({
        p <- base_histogram
        
        current <- table_data()
        if (nrow(current) > 0) {
            p <- p + geom_histogram(data = current, fill = "red", bins = 30)
        }

        p
    })
    
    table_data <- reactive({
        print("called")
        brushedPoints(df, input$brush)
    })
}

# Run the application 
shinyApp(ui = ui, server = server)

在这个玩具示例中,它几乎不引人注意。但是在我的完整应用程序中,必须在 table_data 响应式中进行大量计算,而这种双重调用会不必要地减慢一切。

有没有什么方法可以构建应用程序,以便在画笔结束时只执行一次反应?


这是一个 GIF,显示每次画笔都会执行两次 table_data

【问题讨论】:

    标签: r ggplot2 shiny reactive brush


    【解决方案1】:

    试试这个,每次画笔移动时只触发一次。

    library(ggplot2)
    library(shiny)
    
    df <- data.frame(x = rnorm(1000))
    base_histogram <- ggplot(df, aes(x)) +
        geom_histogram(bins = 30)
    
    # Define UI for application that draws a histogram
    ui <- fluidPage(
        column(
            plotOutput("histogram", brush = brushOpts(direction = "x", id = "brush", delay=500, delayType = "debounce")),
            width = 6
        )
    )
    
    # Define server logic required to draw a histogram
    server <- function(input, output) {
        output$histogram <- renderPlot({
            p <- base_histogram
            
            if(!is.null(table_data())) {
                p <- p + geom_histogram(data = table_data(), fill = "red", bins = 30)
            }
            p
        })
        
        table_data <- reactive({
            if(is.null(input$brush)) return()
            print("called")
            brushedPoints(df, input$brush)
        })
    }
    
    shinyApp(ui, server)
    

    【讨论】:

    • 这似乎仍然无法正常工作。使用此答案中的代码时,我已使用显示打印输出的图像更新了我的问题。
    • 在我的浏览器中工作。也许您正在使用不同的浏览器或不同的系统,或者您的选择速度太慢。但是,无论您如何尝试解决问题,我意识到最大的问题是 Shiny 没有 mouse-up 事件侦听器。这意味着当您按住鼠标进行选择时,选择区域的值会不断变化,而不是在您松开鼠标时取最终值。除非您进行自定义 javascript hack,否则无法使用当前版本的 Shiny 进行修复。
    • 你说得对——我一直在 rstudio 窗口中查看它。在普通浏览器中,它不会多次调用。关于鼠标向上的观点是有道理的;我需要一些更自定义的东西来获得这么多的控​​制。
    猜你喜欢
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 2015-03-05
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    相关资源
    最近更新 更多