0

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)
mattek
  • 903
  • 1
  • 6
  • 18

1 Answers1

2

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)
  

output

YBS
  • 19,324
  • 2
  • 9
  • 27
  • That is great, thank you! Any idea how that would work if there were two layers with different geoms? In fact, in my original problem I have `geom_point` that exists at all time points and `geom_tile` that exists in only a part of them. – mattek Sep 24 '20 at 10:01
  • Just after `geom_point()+`, you can add `geom_tile(data=subset(dtP, dtp=="dtP2"), aes(x=x, y=y)) +`. Then you will get a tile moving from top left to bottom right. – YBS Sep 24 '20 at 17:21
  • That's the thing, it doesn't produce the desired result. The tile appears at time points `1-7` instead of `{2, 5, 8}`. I've made a separate [question](https://stackoverflow.com/q/64047537/1898713) to address that. – mattek Sep 25 '20 at 07:04