首页 > 解决方案 > gganimate 不显示所有帧

问题描述

我想做一个有 138个状态的简单 gif 。我不需要在每个状态之间进行任何花哨的转换,但我确实需要每个状态都出现在我的 gif 中。目前,gganimate正在缩短我的 gif,没有透露最后约 30 个状态。

例子

df <- lapply(1:138, function(t){
  data.frame(
    DT = as.POSIXct("2019-01-01 12:00:00", tz = "UTC") + t*24*60*60,
    x = seq(-3, 3, length.out = 100),
    y = t * seq(-3, 3, length.out = 100)
  )
})
df <- do.call(rbind, df)
range(df$DT)  # "2019-01-02 12:00:00 UTC" "2019-05-19 12:00:00 UTC"

p <- ggplot(data = df, mapping = aes(x = x, y = y)) + 
  geom_point()+ 
  transition_states(states = DT, transition_length = 0, state_length = 1)+
  labs(title = 'ScrapeDT: {previous_state}')
p

在此处输入图像描述

如您所见,gif 将播放到大约 2019-04-10,而不是 2019-05-19。我也尝试过修补animate()但没有成功。例如,

animate(
  plot = p, 
  nframes = length(unique(df$DT)), 
  fps = 8, 
  end_pause = 8
)

在此处输入图像描述

我怎样才能使这项工作能够显示每个所需的状态,例如 0.25 秒?

标签: ranimated-gifgganimate

解决方案


文档中所述,transition_manual()这正是您所需要的:

此转换允许您将数据中的变量映射到动画中的特定帧。不会对数据进行补间,动画中的帧数将由 frame 变量中的级别数决定。

注意我在下面用transition_manual()and做了什么labs()

library(tidyverse)
library(gganimate)

df <- lapply(1:138, function(t){
  data.frame(
    DT = as.POSIXct("2019-01-01 12:00:00", tz = "UTC") + t * 24 * 60 * 60,
    x = seq(-3, 3, length.out = 100),
    y = t * seq(-3, 3, length.out = 100)
  )
})
df <- do.call(rbind, df)

p <- ggplot(data = df, mapping = aes(x = x, y = y)) + 
  geom_point()+ 
  transition_manual(frames = DT)+
  labs(title = 'ScrapeDT: {current_frame}')

animate(
  plot = p, 
  nframes = length(unique(df$DT)), 
  fps = 4, 
  end_pause = 8
)

工作动画 gif


推荐阅读