R语言学习(九)动态制图——gganimater包

gganimater包和之前的3d包一样,是对ggplot2包的扩展,主要是描绘图表的动态变化。

GitHub——链接https://github.com/thomasp85/gganimate

安装

# install.packages('devtools')
devtools::install_github('thomasp85/gganimate')

示例1——动态箱图

library(ggplot2)
library(gganimate)
library(gifski)
ggplot(mtcars, aes(factor(cyl), mpg)) + 
  geom_boxplot() + 
  # Here comes the gganimate code
  transition_states(
    gear,
    transition_length = 2,
    state_length = 1
  ) +
  enter_fade() + 
  exit_shrink() +
  ease_aes('sine-in-out')

这里需要安装一个和生成gif格式相关的gifski包。 transition_states是按照给定的列分成不同时态的数据动态显示,这里是将数据按照给定的gear列分成不同组,一组组显示得到动态图。 transition_length为相对的转换时间, state_length为相对的状态停留的时间。enter_fade() 、exit_shrink()、ease_aes(‘sine-in-out’)似乎为某种动画渐变效果(简介太复杂了嘤嘤嘤)。

在这里插入图片描述

示例2——动态散点图

这种散点图的动态效果,简直萌化了老夫的少女心!!

library(gapminder)

ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
  geom_point(alpha = 0.7, show.legend = FALSE) +
  scale_colour_manual(values = country_colors) +
  scale_size(range = c(2, 12)) +
  scale_x_log10() +
  facet_wrap(~continent) +
  # Here comes the gganimate specific bits
  labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') +
  transition_time(year) +
  ease_aes('linear')

gapminder为各国gdp、生活质量的数据集。 transition_time作用和ransition_states差不多,唯一区别是变化时间长度不再是固定数值,而是选定列数据之间差值,假如选定的列数据为年份,那么年份相隔近的数据变化时间要比相隔远的数据时间短。
在这里插入图片描述

作者原页面还提供了关于将其导出为视频格式的代码。

ease_aes() 函数详解

指定动画在不同点上的行进速度
示例:
 ease_aes('linear')
 ease_aes('linear-in')
ease_aes('linear-in-out') 

参数:

这里的参数模型是动画的速度曲线,in,out还要in-out则表示函数的凸凹变化,先凸后凹还是先凹后凸。
在这里插入图片描述

这里举个例子,因为找不到好的资料,就把前端类似的图搬过来,下图为不同模型的速度(仅作参考)
在这里插入图片描述

效果显示:

在这里插入图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值