R";“实时”;未在RShiny中显示的绘图

R";“实时”;未在RShiny中显示的绘图,r,animation,plot,shiny,R,Animation,Plot,Shiny,我试图让我的RShiny应用程序显示一个有点实时的条形图。基本上,逻辑是这样的:RShiny将建立到一个文件的连接,并不断地从中读取,直到它到达文件的末尾。该文件也将被更新。我的server.R代码如下: library(stringr) shinyServer ( function(input, output, session) { output$plot1.3 = renderPlot({ con = file("C:/file.csv", open = "r") a =

我试图让我的RShiny应用程序显示一个有点实时的条形图。基本上,逻辑是这样的:RShiny将建立到一个文件的连接,并不断地从中读取,直到它到达文件的末尾。该文件也将被更新。我的server.R代码如下:

library(stringr)

shinyServer
(
 function(input, output, session)
 { 

output$plot1.3 = renderPlot({
  con  = file("C:/file.csv", open = "r")
  a = c()
  while (length((oneLine = readLines(con, n = 1, warn = F))) > 0) 
  {
    #constructing vector
    a = c(a, str_extract(oneLine, "\\[[A-Z]+\\]"))
    #making vector into a table
    b = table(a)
    #plotting the table
    barplot(b, xlim = c(0,10), ylim = c(0,1000), las = 2, col = rainbow(5))
    #Sleeping for 1 second to achieve a "animation" feel
    Sys.sleep(1)
  } 
  close(con)
})

}
)


我知道我在这里试图做的是低效的,因为我不断地重建一个向量,并从中生成一个表,然后为每次迭代重新填充,但这段代码在RStudio上运行得非常好,但只有在最后一次迭代完成时(当达到EOF时),绘图才会出现在我的RShiny应用程序上。发生了什么?

发生的事情是,在调用
renderPlot()
返回之前,浏览器没有任何显示内容,而这只是在所有while循环结束时才会执行

@Shiva建议让您的数据具有反应性(并提供完整的代码)。我完全同意,但还有更多

最好的选择是使用一对工具,闪亮的
reactiveTimer
ggvis
渲染

首先,您将定义数据,如下所示:

# any reactive context that calls this function will refresh once a second
makeFrame <- reactiveTimer(1000, session) 

# now define your data
b <- reactive({
     # refresh once a second
     makeFrame()
     # here put whatever code is used to create current data
     data.frame([you'll need to have your data in data.frame form rather than table form])
})
然后一切看起来都会很漂亮。如果需要,还应该很容易找到示例代码,让用户启动和停止动画或设置帧速率


如果您发布了一个可复制性最低的示例,我将尝试停下来编辑代码以发挥作用。

您需要使数据具有反应性,并将反应性数据发送到
renderPlot()
此外,提供您的整个代码(使其具有可复制性)可能会对您和我们有所帮助。
 b %>% # passing the reactive function, not its output!
      ggvis([a bunch of code to define your plot]) %>%
      layer_bars([more code to define your plot]) %>%
      bind_shiny("nameofplotmatchingsomethinginoutput.ui")