嗨我有以下代码,我用它来查看使用MASS包的协方差矩阵的行为
library(MASS)
library(ggplot2)
for(x in 0:100){
mycor = x/100
mydist = mvrnorm(100, c(5,10), matrix(c(1,mycor,mycor,1), 2),
empirical=TRUE)
md = data.frame(mydist)
colnames(md)= c('x','y')
graph = ggplot(md, aes(x,y)) + geom_point() +
stat_smooth(method='lm',color='red') +
stat_smooth(method='loess',se=FALSE,color='blue')
print(graph)
Sys.sleep(0.05)
}
如果我可以将快照转换为动画序列,那就太好了。有什么方法可以用R做到吗?
由于
答案 0 :(得分:2)
好吧,首先安装imagemagick,它的小和ez。然后你可以做以下事情:
## Make a directory to store pngs temp
dir.create("~/example")
setwd("~/example")
for(x in 0:100){
mycor = x/100
mydist = mvrnorm(100, c(5,10), matrix(c(1,mycor,mycor,1), 2),
empirical=TRUE)
md = data.frame(mydist)
colnames(md)= c('x','y')
graph = ggplot(md, aes(x,y)) + geom_point() +
stat_smooth(method='lm',color='red') +
stat_smooth(method='loess',se=FALSE,color='blue')
ggsave(filename = sprintf("%02d.png", x))
## print(graph)
## Sys.sleep(0.05)
}
这最后一步只是从所有.png中删除.gif然后删除它们。命令通过命令行发送到imagemagick。
## Not sure if you on Linux or windows
dev.off()
if (Sys.info()[['sysname']] == "Linux") {
system("convert -delay 80 *.png example.gif")
} else { shell('"convert -delay 80 *.png example.gif"') }
file.remove(list.files(path = "~/example/", pattern=".png"))
答案 1 :(得分:2)
animation package提供了许多功能,可以轻松完成。 (包括imagemagick的包装器)。
您的示例,使用SciAnimator库创建HTML文件
library(animation)
saveHTML({
for(x in 0:100){
mycor = x/100
mydist = mvrnorm(100, c(5,10), matrix(c(1,mycor,mycor,1), 2),
empirical=TRUE)
md = data.frame(mydist)
colnames(md)= c('x','y')
graph = ggplot(md, aes(x,y)) + geom_point() +
stat_smooth(method='lm',color='red') +
stat_smooth(method='loess',se=FALSE,color='blue')
print(graph)
}
}, img.name = "cor_plot", imgdir = "cor_dir", htmlfile = "cor.html", autobrowse = FALSE, outdir = getwd())