首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过gganimate和ggforce的移动小块缩放的动画情节?

通过gganimate和ggforce的移动小块缩放的动画情节?
EN

Stack Overflow用户
提问于 2018-10-17 16:13:13
回答 1查看 1.9K关注 0票数 23

目标

我想放大几年来Europe的国内生产总值。幻象ggforce::facet_zoom非常容易地允许静态地块(即特定年份)这样做。

然而,事实证明,移动比例尺比预期更难。gganimate似乎从第一个帧(year == 1952)开始使用x轴限制,并一直延续到动画的末尾。This related, but code-wise outdated question did not yield an answer, unfortunately+ coord_cartesian(xlim = c(from, to))facet_zoom(xlim = c(from, to))似乎都无法超越静态限制来影响facet_zoom窗口。

  • gganimate 有没有办法让为每一帧重新计算 facet_zoom 的标度?

理想结果

第一帧

最后帧

当前代码

代码语言:javascript
复制
library(gapminder)
library(ggplot2)
library(gganimate)
library(ggforce)
p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent)) +
    geom_point() + scale_x_log10() +
    facet_zoom(x = continent == "Europe") +
    labs(title = "{frame_time}") +
    transition_time(year) 

animate(p, nframes = 30)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-27 00:03:58

我不认为目前的gganimate开发版本到2018年12月还不太可能;似乎有一些bug阻碍了facet_zoomgganimate的好感。幸运的是,我不认为解决办法太痛苦。

首先,我们可以在中间年份填写:

代码语言:javascript
复制
# Here I tween by fractional years for more smooth movement
years_all <- seq(min(gapminder$year), 
                 max(gapminder$year), 
                 by = 0.5)

gapminder_tweened <- gapminder %>%
  tweenr::tween_components(time = year, 
                           id   = country, 
                           ease = "linear", 
                           nframes = length(years_all))

然后,将代码应用到一个需要一年作为输入的函数中:

代码语言:javascript
复制
render_frame <- function(yr) {
  p <- gapminder_tweened %>%
    filter(year == yr) %>%
    ggplot(aes(gdpPercap, lifeExp, size = pop, color = continent)) +
    geom_point() +
    scale_x_log10(labels = scales::dollar_format(largest_with_cents = 0)) +
    scale_size_area(breaks = 1E7*10^0:3, labels = scales::comma) +
    facet_zoom(x = continent == "Europe") +
    labs(title = round(yr + 0.01) %>% as.integer) 
    # + 0.01 above is a hack to override R's default "0.5 rounds to the
    #   closest even" behavior, which in this case gives more frames
    #   (5 vs. 3) to the even years than the odd years
  print(p) 
}  

最后,我们可以通过遍历多年(在本例中包括小数年)来保存动画:

代码语言:javascript
复制
library(animation)
oopt = ani.options(interval = 1/10)
saveGIF({for (i in 1:length(years_all)) {
  render_frame(years_all[i])
  print(paste0(i, " out of ",length(years_all)))
  ani.pause()}
},movie.name="facet_zoom.gif",ani.width = 400, ani.height = 300) 

或者,也可以将gifski用于小于2MB的较小文件:

代码语言:javascript
复制
gifski::save_gif({ for (i in 1:length(years_all) {
  render_frame(years_all[i])
  print(paste0(i, " out of ",length(years_all)))
}
},gif_file ="facet_zoom.gif", width = 400, height = 300, delay = 1/10, progress = TRUE) 

(当我有更多的时间时,我将尝试通过使用手动指定的中断来消除传说中的干扰变化。)

票数 31
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52859316

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档