0
votes

I want to build an app that will start plotting after a press of a button and it will keep plotting (with some time in between graphs) until the for cycle has ended. The function that calculates what to plot is rather elaborate so I will provide a minimal working example from base R, that I want to run in shiny. Again I'm not sure how to approach this, so I can't provide the code in terms of server.r and ui.r.

for (i in 1:10){
    A <- matrix(nrow=5,ncol =5,sample(3,size =25,replace=T))
    Sys.sleep(0.3)
    image(A,xaxt='n', ann=FALSE,yaxt='n',bty="n",asp=1)
}

How should I approach this?

I think I will be able to make the progress bar work myself, but the continuous plotting stopped me from doing anything.

1

1 Answers

0
votes

Well, I guess I'm an Idiot and I found a similar problem discussed here (ofcourse 30 minutes after posting this) and I was able to adapt the code. Hope this helps someone in the future.

library(shiny)

ui <- fluidPage(
  shinyjs::useShinyjs(),
  tags$style(type="text/css",
             ".recalculating {opacity: 1.0;}"),
      mainPanel(
        actionButton("Start","START", width='100%'),
        plotOutput("A")
      )
   )


server <- function(input, output, session) {
  par(bg = 'black')
  maxIter <- 5
  vals <- reactiveValues( A = matrix(nrow=5,ncol =5,sample(3,size =25,replace=T)),counter = 1)
  observeEvent(input$Start, {
    vals$counter <- 1 
    shinyjs::disable("Start")
    output$A <- renderPlot({
       Sys.sleep(0.5)
       image(vals$A,xaxt='n', ann=FALSE,yaxt='n',bty="n",asp=1)

       })


  })

     observeEvent(input$Start, {
                                observe({
                                        isolate({
                                              vals$A <- matrix(nrow=5,ncol =5,sample(3,size =25,replace=T))
                                              vals$counter <- vals$counter + 1 #for loop

                                              })

                                        if (isolate(vals$counter) <= maxIter) 
                                                invalidateLater(0, session)
                                        })
                                  })
     observe({vals$counter
       if (vals$counter > maxIter)
         shinyjs::enable("Start")
       })
}
shinyApp(ui = ui, server = server)