簡體   English   中英

在R中將一系列繪圖轉換為動畫序列

[英]Converting a series of plots into an animated sequence in R

嗨,我有以下代碼可用來使用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做到這一點嗎?

謝謝

好吧,首先安裝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)
 }

最后一步只是將.gif從所有.png中分離出來,然后將其刪除。 這些命令通過命令行發送到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"))

動畫包提供了許多使此操作變得容易的功能。 (包括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())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM