直接上代碼
方法一:
library(magick)library(ggplot2)library(gganimate)library(ggthemes)
library(gapminder)View(gapminder)table(gapminder$year)
for (i in 1:length(unique(gapminder$year))) { ggplot(data = gapminder[gapminder$year == as.numeric(names(table(gapminder$year))[i]),], aes(x = gdpPercap, y = lifeExp, size = pop, color = continent)) + geom_point(alpha = 0.5) + scale_x_log10() + theme_bw() + labs(title = paste("Year",names(table(gapminder$year))[i], sep = " "), x = "GDP per capita", y = "life expectancy") + guides(size = guide_legend(order = 1), color = guide_legend(order = 2)) + theme(legend.key.size = unit(0.25, "cm"), legend.key.width = unit(0.15,"cm")) + ggsave(filename = paste0(names(table(gapminder$year))[i],".png"), width = 10, height = 6, units = "cm")}
animate_p <- image_animate(image = image_read(path = paste0(names(table(gapminder$year)), ".png")))anim_save(filename = "anim.gif", animation = animate_p, path = "./")
總結一下:這張圖其實應該在上面的循環中應該繪製一樣的大小,然後在合併圖片的時候才能展示出比較好的結果。
方法二:
ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent)) + geom_point() + scale_x_log10() + theme_bw() + labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') + transition_time(year) + ease_aes('linear')
anim_save("gganimate1.gif")
總結一下:gganimate包的使用參數還是很多的,以後還需要慢慢學習。
可以發現這個包可以完全的把每一年的數據很好的整合到一起去。
對上面的結果進行分面
facet_wrap
ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, fill = country)) + geom_point(shape = 21,alpha = 0.7, show.legend = F) + scale_colour_manual(values = country_colors) + scale_size(range = c(2, 20)) + scale_x_log10() + facet_wrap(~continent,nrow = 1,scales = "free_y") + labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') + transition_time(year) + ease_aes('linear')anim_save("gganimate2.gif")
R繪圖動態圖的包的參數還有很多,仍需要繼續學習!