Force shiny to render plot in loop

后端 未结 1 643
不知归路
不知归路 2021-01-14 13:51

I have a shiny app that runs a simulation. The goal is to show the user the calculation steps in between as a plot.

How do I force shiny to update the plot?

相关标签:
1条回答
  • 2021-01-14 14:03

    You could nest an observer into an observeEvent to make it work. Based on Jeff Allen's code from the SO topic you linked.

    Crucial part:

    observeEvent(input$run, {
        rv$i <- 0
        observe({
          isolate({
            rv$i <- rv$i + 1
          })
    
          if (isolate(rv$i) < maxIter){
            invalidateLater(2000, session)
          }
        })
      })
    

    Full code:

    library(shiny)
    
    server <- function(input, output, session) {
      rv <- reactiveValues(i = 0)
      maxIter <- 3
    
      output$myplot <- renderPlot( {
        if(rv$i > 0) {
          x <- seq_len(rv$i * 100)
          y <- (x + 1)^2 - 1 # this will do for now
          plot(x, y, main = sprintf("Round %i", rv$i), type = "l") 
        } else {
          plot(1:1, main = "Placeholder")
        }
      })
    
      observeEvent(input$run, {
        rv$i <- 0
        observe({
          isolate({
            rv$i <- rv$i + 1
          })
    
          if (isolate(rv$i) < maxIter){
            invalidateLater(2000, session)
          }
        })
      })
    
    }
    
    ui <- fluidPage(
      actionButton("run", "START"),
      plotOutput("myplot")
    )
    
    shinyApp(ui = ui, server = server)
    
    0 讨论(0)
提交回复
热议问题