Is there a way to display plots as they build in Shiny instead of waiting for all of them?

我的梦境 提交于 2019-12-04 07:46:21

You can use reactiveTimer() to refresh your page regularly.

And you can save your plots in a list of plots to print them immediately at each refresh.

I had to reorder the renderPlot functions so the step iterator only renders one plot at a time

Also I chose not to start the first render right away to plot "Loading" plots.

library(shiny)

ui <- fluidPage( 
  title = "Page loading test"
  , h1("Page loading test")
  , plotOutput("plot1")
  , plotOutput("plot2")
  , plotOutput("plot3")
  , plotOutput("plot4")
)

# Loading plot
plot(-1:1, -1:1, type = "n", xlab = "", ylab = "")
text(0,0, "Loading",cex = 5)
loading <- recordPlot()

plotlist <- vector("list",4) 
step <- 0 # which plot should be rendered next

server <- function(input, output, session) {
  autoInvalidate <- reactiveTimer(10, session)
  output$plot4 <- renderPlot({autoInvalidate();
    if(step>4){plotlist[[4]]}
    else if(step==4){step <<- step+1
    print("rendering step 4")
    Sys.sleep(10)
    plotlist[[4]] <<- {plot(rnorm(50));recordPlot()}} else loading
  })
  output$plot3 <- renderPlot({autoInvalidate();
    if(step>3){plotlist[[3]]}
    else if(step==3){step <<- step+1
    print("rendering step 3")
    Sys.sleep(10)
    plotlist[[3]] <<- {plot(rnorm(50));recordPlot()}} else loading
  })
  output$plot2 <- renderPlot({autoInvalidate();
    if(step>2){plotlist[[2]]}
    else if(step==2){step <<- step+1
    print("rendering step 2")
    Sys.sleep(10)
    plotlist[[2]] <<- {plot(rnorm(50));recordPlot()}} else loading
  })
  output$plot1 <- renderPlot({autoInvalidate();
    if(step>1){plotlist[[1]]}
    else if(step==1){step <<- step+1
    print("rendering step 1")
    Sys.sleep(10)
    plotlist[[1]] <<- {plot(rnorm(50));recordPlot()}} else {step <<-1;loading}
  })
}
shinyApp(ui = ui, server = server)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!