我正在嘗試制作一個在用戶單擊某個點后顯示一些資料的應用程式。它可以作業,除了當資料長于視窗時,滾動條會顯示,調整繪圖大小并洗掉資料。如何讓資料顯示和停留?
下面是一個最小示例的代碼。
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)
uj5u.com熱心網友回復:
這里的問題是,一旦垂直滾動條出現,plotOutput就會調整大小并因此重新渲染,這會導致input$plot_click重置為NULL空表。
我們可以使用req()'cancelOutput引數來避免這種行為。
請參閱?req:
cancelOutput:如果 TRUE 并且正在評估輸出,則照常停止處理,但不清除輸出,而是將其保持在它碰巧處于的任何狀態。
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/478910.html
上一篇:如何在R中生成帶注釋的每月熱圖?
