R: "InvalidArgument ` -delay' 带动画和 ggplot

标签 r animation ggplot2

我试图从一个大数据集(来自一个循环科学实验)在 R 中制作一个动画图,以可视化两个变量随时间的变化。我正在使用 animation库只是简单地:

saveGIF(
    for(i in 1:100){
    mygraph(i)
}, interval = 0.1, ani.width = 640, ani.height = 480)

哪里mygraph(i)只绘制循环 i 的图形。如果我使用 plot()制作图形,然后它工作得很好,但是如果我改为使用 ggplot(我想这样做,因为我最终想用它来制作更复杂的图),那么它不起作用,我得到以下输出:
Executing: 
'convert' -loop 0 -delay 'animation.gif'
convert: InvalidArgument `-delay': animation.gif @ error/convert.c/ConvertImageCommand/1161.
an error occurred in the conversion... see Notes in ?im.convert
[1] FALSE 

我对 R 很陌生,所以我有点卡住了,而且我还没有通过查看 ?im.convert 找到解决方案。或从四处寻找。任何建议将不胜感激...

根据要求使用虚拟数据的示例:
library(animation)
library(ggplot2)

x <- 1:20
y <- 21:40
z <- c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4)
data <- data.frame(x,y,z)

mygraph <- function(i) {
  plot(data$x[data$z == i], 
       data$y[data$z == i], 
       title(title))
}

saveGIF(
  for(i in 1:4){
    title <- paste("Cycle", i, sep=" ")
    mygraph(i)
  }, interval = 0.5, ani.width = 640, ani.height = 480)

这有效,但如果函数 mygraph而是:
mygraph <- function(i) {
  ggplot() +
    geom_point(aes(x=data$x[data$z == i], y=data$x[data$z == i]))
}

...然后它给了我如上所述的错误。

最佳答案

如果您包装 ggplot,这似乎有效在 print()声明,例如

mygraph <- function(i) {
  g <- ggplot() +
    geom_point(aes(x=data$x[data$z == i], y=data$x[data$z == i]))
  print(g)
}

这是 R-FAQ 7.22 的变体,Why do lattice/trellis graphics not work?

关于R: "InvalidArgument ` -delay' 带动画和 ggplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28810305/

相关文章:

在不中断for循环的情况下重新启动R session

javascript - 如何在成帧器运动中多次使用动画

r - 为什么不应该在 R 包中使用 library() 或 require()

r - 将函数参数传递给 dplyr select

R 意外地将字段从 CSV 文件转换为 NA

javascript - 移除 child 时动画 parent

r - ggplot : adding color aesthetic changes stack order

r - 使用 ggplot 标记异常值

r - 具有 NULL 名称的对象上的 all.equal 会导致 'Error: not compatible with STRSXP'——错误还是预期?

android - 使用 nineoldandroids 库时动画 setInterpolator() 不工作