当滚动条出现时,具有 nearPoints 的闪亮应用程序会闪烁数据

Shiny app with nearPoints flashes data when scrollbar appears

我正在尝试制作一个在用户单击某个点后显示一些数据的应用程序。它有效,除了当数据长于 window 时,滚动条出现,调整绘图大小并擦除数据。如何让数据展现并留下来?

下面是一个最小示例的代码。

library(shiny)
library(tidyr)

ui <- fluidPage(
  plotOutput("plot", click = "plot_click"),
  tableOutput("data")
)
server <- function(input, output, session) {
  output$plot <- renderPlot({
    ggplot(mtcars, aes(wt, mpg)) + geom_point()
  }, res = 96)
  
  output$data <- renderTable({
    req(input$plot_click)
    np <- nearPoints(mtcars, input$plot_click) %>% 
      pull(gear)
    mtcars %>% 
      filter(gear == np)
  })
}

shinyApp(ui = ui, server = server)

这里的问题是,一旦垂直滚动条出现,plotOutput 就会调整大小,因此 re-rendered,这会导致 input$plot_click 被重置为 NULL,从而导致空 table.

我们可以使用 req()cancelOutput 参数来避免这种行为。

请参阅?req:

cancelOutput: If TRUE and an output is being evaluated, stop processing as usual but instead of clearing the output, leave it in whatever state it happens to be in.

library(shiny)
library(tidyr)
library(dplyr)
library(ggplot2)

ui <- fluidPage(
  plotOutput("plot", click = "plot_click"),
  tableOutput("data")
)
server <- function(input, output, session) {
  output$plot <- renderPlot({
    ggplot(mtcars, aes(wt, mpg)) + geom_point()
  }, res = 96)
  
  output$data <- renderTable({
    req(input$plot_click, cancelOutput = TRUE)
    np <- nearPoints(mtcars, input$plot_click) %>% pull(gear)
    if(length(np) > 0){
      mtcars %>% filter(gear == np)
    } else {
      NULL
    }
  })
}

shinyApp(ui = ui, server = server)