R制作動(dòng)畫的本質(zhì),是將一系列的圖片僧著,合成一張gif格式的圖片
可以舉個(gè)簡(jiǎn)單的例子:
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生成的對(duì)象遭商,構(gòu)建動(dòng)態(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工具包劫流,在制作動(dòng)畫過程中,依然需要調(diào)用ImageMagick軟件丛忆。
271_gganimate.gif