Search code examples
rggplot2gganimate

Animating persistent data points at irregular times


I am trying to animate data points to appear at specific times. The data points are not linked to each other, so there should be no trails to/from them. They should just appear at the appointed time and place.

However, possibly due to the nature of the irregularly time intervals and the frame rendering, there appears to be a lot of lead-in. It is really noticeable before a data point that has a long interval preceding it.

I've messed with shadow_trail(), shadow_wake(), nframes in animate(), plus some of the other transition_*() functions to no avail.

Here's a code example of a 10x10 grid where each square pops up at a time specified in the data, but not at any regular interval. You can see that some of the squares travel to their destination. They should just appear in-place.

library(ggplot2)
library(gganimate)

pos <- seq(1, 100, 1)

# Squares on a 10x10 grid that pop up at random times
grid_data <- data.frame(pct = pos,
                        t = rnorm(100, mean=50, sd=25),
                        xpos = (pos-1) %% 10,
                        ypos = floor((pos-1) / 10))

p <- ggplot(grid_data, aes(x=xpos, y=ypos, fill=t))  # plot tiles, color by time of arrival 
p <- p + geom_tile(aes(width=0.95, height=0.95))     # tiles with some gap around them 
p <- p + transition_time(time=grid_data$t)           # Show data points by their time
p <- p + shadow_mark(past=TRUE, future=FALSE)        # Keep showing past (prior) data points

animate(p)

enter image description here


Solution

  • I think what is happening is that when you are using transition_time your transitions are 'travelling' from one tile to the next. You can prevent this by using transition_reveal instead.

    Try this:

    library(ggplot2)
    library(gganimate)
    
    pos <- seq(1, 100, 1)
    
    grid_data <- data.frame(pct = pos,
        t = rnorm(100, mean=50, sd=25),
        xpos = (pos-1) %% 10,
        ypos = floor((pos-1) / 10))
    
    grid_data %>%
      ggplot() +
        aes(x=xpos, y=ypos, fill=t) + 
        geom_tile(aes(width=0.95, height=0.95)) +   
        transition_reveal(pct, t, keep_last = TRUE) +
        anim_save("animated_geom_tile.gif")
    

    Which produces this...

    enter image description here