强制闪亮以在循环中渲染图 [英] Force shiny to render plot in loop

查看:89
本文介绍了强制闪亮以在循环中渲染图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个运行模拟的闪亮应用程序.目的是向用户显示介于两者之间的计算步骤.

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

如何强制更新地图?

MWE看起来像这样

library(shiny)

server <- function(input, output, session) {
  # base plot as a placeholder
  output$myplot <- renderPlot(plot(1:1, main = "Placeholder"))

  # wait until the button is triggered
  observeEvent(input$run, {
    print("Do some calculations in 3 steps")
    for (i in seq_len(3)) {
      print("Do some calculations")
      # ...
      x <- seq_len(i * 100)
      y <- (x + 1)^2 - 1 # this will do for now

      print("Plot the data ")

      # ISSUE HERE!
      # this should render the current step of the simulation, instead it 
      # renders only after the whole code is run (i.e., after step 3)
      output$myplot <- renderPlot(plot(x, y, main = sprintf("Round %i", i), type = "l"))

      print("Wait for 1 second for the user to appreciate the plot...")
      Sys.sleep(1)
    }
  })
}

ui <- fluidPage(
  actionButton("run", "START"),
  plotOutput("myplot")
)

shinyApp(ui = ui, server = server)

问题是,shiny运行代码并在模拟结束时生成一个图,但是,我想在每个模拟步骤中获得一个图(显示至少一秒钟).

The issue is, that shiny runs the code and produces one plot at the end of the simulation, however, I want to get a plot at each simulation step (displayed for at least one second).

非常感谢您的帮助/提示.

Any help/hint is greatly appreciated.

我查看了此帖子,但将其替换带有plot/renderPlot的文本不能产生正确的结果.

I have looked at this post, but replacing the text with a plot/renderPlot doesn't yield the correct results.

推荐答案

您可以将observer嵌套到observeEvent中以使其起作用.基于您链接的SO主题中Jeff Allen的代码.

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

关键部分:

observeEvent(input$run, {
    rv$i <- 0
    observe({
      isolate({
        rv$i <- rv$i + 1
      })

      if (isolate(rv$i) < maxIter){
        invalidateLater(2000, session)
      }
    })
  })

完整代码:

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)

这篇关于强制闪亮以在循环中渲染图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆