library(gapminder)#加载 gapminder 包,其中包含了从 1952 年至 2007 年各个国家的 GDP、预期寿命和人口数据
library(gganimate)#加载 gganimate 包,它提供了创建动画的功能
library(ggplot2)
#使用 ggplot() 函数创建了一个基础图形,设置 x 轴为 GDP 每人,y 轴为预期寿命,点的大小(size)和颜色(colour)根据国家来区分
ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
geom_point(alpha = 0.7, show.legend = FALSE) + #添加了散点图层,设置点的透明度为 0.7,且不显示图例
scale_colour_manual(values = country_colors) + #设置颜色映射为手动指定的颜色,country_colors 是一个预先定义的颜色向量
scale_size(range = c(2, 12)) + #设置点的大小范围为 2 到 12
scale_x_log10() + #将 x 轴的刻度设置为对数尺度
facet_wrap(~continent) + #根据大洲进行面板分割
labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') + #设置图形的标题、x 轴标签和 y 轴标签,其中 {frame_time} 会被动画帧的时间替换
transition_time(year) + #指定以年份(year)为时间变量进行过渡,使得动画按照时间的变化进行播放
ease_aes('linear') -> anim #设置动画的渐变效果为线性,将动画保存到名为 anim 的对象中
#生成并显示动画,使用 gifski_renderer() 渲染器,并设置帧率为 10
animate(anim, renderer = gifski_renderer(), fps = 10)