2014-03-05 80 views
0

嗨,我有以下的代碼,我使用的大容量包裝R中轉換一個序列圖到動畫序列

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

是6pool感謝 –

回答

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")) 
+0

在Linux上,但出於完整性偉大的答案創建一個HTML文件 –

2

animation package提供了許多功能,這將使這很容易。 (包括imagemagick的包裝)。

你舉的例子,使用SciAnimator庫

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())