嗨,我有以下代码,我正在使用 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做到这一点吗?
谢谢
好吧,首先安装图像魔术,它很小。然后,您可以执行以下操作:
## 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"))
动画包提供了许多功能,使这变得容易。(包括图像魔术的包装器)。
您的示例,使用 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())