【发布时间】:2011-06-21 18:33:13
【问题描述】:
【问题讨论】:
标签: r animation plot time-series
【问题讨论】:
标签: r animation plot time-series
两个要点:
老派的技巧是在循环中单独编写一系列 gif 文件,然后使用 imagemagick 之类的工具将它们“粘合”成动画 gif
还有更高级别的软件包,例如获奖的animation,可以帮助解决这个问题;某些功能可能依赖于平台
【讨论】:
这里有一些基本代码可以帮助您入门(如果它们对您很重要,您可以添加网格线、图例等):
plotfun <- function(x) {
plot( c(-0.5,-0.5,0.5,0.5), c(0,1,1,0), col='blue', xlim=c(-2,2),
type='l', xlab='', ylab='' )
if( x > -1 && x < 0 ) {
polygon( c(-0.5, -0.5, x+0.5, x+0.5), c(0,1,1,0), col='yellow', border=NA )
lines( c(-0.5, -0.5, 0.5, 0.5), c(0,1,1,0), col='blue' )
lines( c(-1,x), c(0,x+1) )
} else if( x >= 0 && x < 1 ) {
polygon( c(x-0.5, x-0.5, 0.5, 0.5), c(0,1,1,0), col='yellow', border=NA )
lines( c(-0.5, -0.5, 0.5, 0.5), c(0,1,1,0), col='blue' )
lines( c(-1,0,x), c(0,1,1-x) )
} else if (x >= 1) {
lines( c(-1,0,1), c(0,1,0) )
}
abline(v=x, lty=3)
lines( c(x-0.5,x-0.5,x+0.5,x+0.5), c(0,1,1,0), col='red' )
}
dev.new(height=3, width=6)
for(i in seq(-2.5, 2.5, 0.05) ) {
plotfun(i)
Sys.sleep(0.1)
}
您可以将 for 循环替换为 repeate 或 while 循环,并控制增量并自动重置以执行多个循环。
您还可以删除 Sys.sleep 并将其放入对 saveMovie、saveHTML 或动画包中的其他函数的调用中,以创建包含动画的文件。
让您通过来回移动滑块来控制动画的另一种方法是:
library(TeachingDemos)
tkexamp( plotfun, list(x=list('slider', from=-2.5, to=2.5, resolution=0.01)),
vscale=1)
【讨论】: