R制作動畫的本質,是將一系列的圖片,合成一張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格式的圖片,之后,通過調用系統 ImageMagick工具包,將png格式轉換成gif格式的圖片
test.gif
除此之外,也有工具包可以直接依據ggplot2生成的對象,構建動態圖,比如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工具包,在制作動畫過程中,依然需要調用ImageMagick軟件。
271_gganimate.gif