我正在尝试让我的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应用程序上。这是怎么回事?
发布于 2015-06-25 13:29:35
实际情况是,在对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])
})如果使用ggvis呈现绘图,ggvis内部就知道如何连接到shiny反应式上下文,以便……哦,不用担心,重点是如果你把b (函数b,而不是b()函数的返回值)输入到ggvis中,它就会平滑地为每次更新做动画处理。
代码将如下所示:
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")然后它就会看起来很漂亮了。如果您愿意,您还可以轻松地找到示例代码,让用户开始和停止动画或设置帧速率。
如果您发布了一个可重复性最低的示例,我将尝试停下来并编辑代码以使其正常工作。
https://stackoverflow.com/questions/31040486
复制相似问题