使用R語言制作動畫

R制作動畫的本質(zhì),是將一系列的圖片,合成一張gif格式的圖片

可以舉個簡單的例子:

png(file="example%02d.png", width=480, height=480)
par(bg="grey")
  for (i in c(10:1, "G0!")){
    plot.new()
    text(.5, .5, i, cex = 6 )
  }
dev.off()

system("convert -delay 20 *.png animated_count_down.gif")
file.remove(list.files(pattern=".png"))

上面的代碼,首先繪制了11張png格式的圖片,之后,通過調(diào)用系統(tǒng) ImageMagick工具包,將png格式轉(zhuǎn)換成gif格式的圖片

test.gif

除此之外,也有工具包可以直接依據(jù)ggplot2生成的對象,構(gòu)建動態(tài)圖,比如gganimate

# Get data:
library(gapminder)

# Charge libraries:
library(ggplot2)
#devtools::install_github("dgrtwo/gganimate")
library(gganimate)
 
# Make a ggplot, but add frame=year: one image per year
p<- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent, frame = year)) +
  geom_point() +
  scale_x_log10() +
  theme_bw()
 
# Make the animation!?
gganimate(p)
 
# Save it to Gif
gganimate(p, "271_gganimate.gif")

需要注意的是,gganimate工具包,在制作動畫過程中,依然需要調(diào)用ImageMagick軟件。

271_gganimate.gif
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。