gganimate: data present only in some frames

主宰稳场 提交于 2021-02-11 17:57:42

问题


I have a problem animating plots where data in some layers in present only in some of the frames. In the example below, I have a moving point that can be nicely animated along 9 frames. However, when I add another layer with a point present only in some of the frames, I get the following error:

Error: time data must be the same class in all layers

Example:

require(data.table)
require(ggplot2)
require(gganimate)

# 9 points along x=y; present at every time point
dtP1 = data.table(x = 1:9,
                  y = 1:9,
                  t = 1:9)

# 3 points along x = 10-y; present at time points 2, 5, 8
dtP2 = data.table(x = c(1, 5, 9),
                  y = c(9, 5, 1),
                  t = c(2, 5, 8))

p = ggplot() +
      geom_point(data = dtP1,
                 aes(x = x,
                     y = y),
                 color = "#000000") +
      geom_point(data = dtP2,
                 aes(x = x,
                     y = y),
                 color = "#FF0000") +
      gganimate::transition_time(t) +
      gganimate::ease_aes('linear')

pAnim = gganimate::animate(p, 
                           renderer = av_renderer("~/test.mp4"), 
                           fps = 1, 
                           nframes = 9,
                           height = 400, width = 400)

回答1:


You can append the data tables and call it as shown below:

  # 9 points along x=y; present at every time point
  dtP1 = data.table(x = 1:9,
                    y = 1:9,
                    t = 1:9,
                    dtp=rep("dtP1",9))
  
  # 3 points along x = 10-y; present at time points 2, 5, 8
  dtP2 = data.table(x = c(1, 5, 9),
                    y = c(9, 5, 1),
                    t = c(2, 5, 8), dtp=rep("dtP2",3))
  dtP <- rbind(dtP1,dtP2)
  
  p = ggplot() +
    geom_point(data = dtP,
               aes(x = x,
                   y = y,
               color = dtp), size=4) +
    
    gganimate::transition_time(t) +
    gganimate::ease_aes('linear')
  
  location <- "C:\\My Disk Space\\_My Work\\RStuff\\GWS\\"
  
  anim_save("usegeom_point2.gif",p,location)
  



来源:https://stackoverflow.com/questions/64037373/gganimate-data-present-only-in-some-frames

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!