【问题标题】:How to make a simple "animation" by redrawing a graph如何通过重绘图表来制作简单的“动画”
【发布时间】:2020-07-22 13:11:41
【问题描述】:

下面的代码在 R Studio 中生成了几乎像动画一样的内容,因为它渲染了 100 个图,每个图的数据都比前一个图略多。

################################################################################
# Visualise probability of heads tending towards 0.5 as more tests performed

# Number of tests to run
tests <-  100

# duration to run for in seconds
durationSeconds <- 10

ht <- sample(c('heads', 'tails'), tests, replace=TRUE)
total <- vector()
for (i in 1:tests) {
  headsAtI <- length(which(ht[1:i] == 'heads'))
  total[i] <- headsAtI/i
  Sys.sleep(durationSeconds/tests)
  plot(total, type='l')
  abline(h = 0.5, col='blue')
}

这可行,但有一些严重的问题:

  1. 创建了 100 个地块,我想理想情况下应该创建并重复使用一个地块
  2. 如果我将“测试”的值更改为 10,000,R Studio 将挂起或崩溃

在 R Studio 中执行此操作的正确方法是什么?

我意识到我可以在最后只画一个情节,包含所有“结果”,但我想实现“动画”效果。

【问题讨论】:

    标签: r


    【解决方案1】:

    你考虑过gganimate吗?

    library(dplyr)
    library(gganimate)
    library(ggplot2)
    
    tests <-  100
    ht <- sample(c('heads', 'tails'), tests, replace=TRUE)
    
    p <- data.frame(ht) %>%
           mutate(headsAtI = cumsum(ht == 'heads'),
                  index = row_number(),
                  total = headsAtI/index) %>%
           ggplot() + aes(index, total) + geom_line() + 
           geom_hline(yintercept = 0.5, color = 'blue') + 
           transition_reveal(index)
    p
    

    【讨论】:

    • 这个解决方案看起来很完美,谢谢,但我在重新创建时遇到了一些麻烦。首先,我收到有关未安装“动画师”的警告,因此我安装并加载了“gifski”,然后收到有关“file_renderer 无法将帧复制到目标目录”的警告。所以我将我的工作目录设置为“setwd”。然后我看到在工作目录中创建了 100 个 .png 文件,但在 RStudio Viewer 中没有 gif/avi 文件和动画。每次重新运行时,我都必须删除 .png 文件,否则会再次出现“file_renderer 无法将帧复制到目标目录”错误。
    • 好像是安装问题。您是否安装了gganimate?如果你没有任何警告/错误,使用上面的代码应该在你的 Rstudio Viewer 中创建上面的图。为了导出它,我使用了另外两个命令。 anim &lt;- animate(p) 和 anim_save("filename.gif", anim) .
    • 这部分运行没有错误或警告: library(dplyr) library(gganimate) library(ggplot2) library(gifski) tests % mutate(headsAtI = cumsum(ht == 'heads'), index = row_number(), total = headsAtI/index) %>% ggplot () + aes(index, total) + geom_line() + geom_hline(yintercept = 0.5, color = 'blue') + transition_reveal(index) p 和 gend 100 个文件,但是行 "anim
    • 这是我能找到的两个帖子stackoverflow.com/questions/60259080/… 和community.rstudio.com/t/… 你有权限写入文件吗?奇怪的是,我没有收到任何警告或错误。
    • 重新启动 Mac OS 修复了它。现在完美运行,感谢美丽的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-21
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多