Search code examples
rggplot2gganimate

Gradually change colour of polygon with gganimate


I'm trying to create an animation where an object is drawn whilst gradually changing its colour. For illustrative purposes assume that the object I want to draw is a circle.

What I have so far

I create a dataset that contains the coordinates of my circle, a time variable and a alpha variable for gradually changing the colour:

t = seq(-pi, pi, length.out = 30)
df <- data.frame(
  x = sin(t), 
  y = cos(t), 
  time = 1:30, 
  alpha = seq(0.1, 1, length.out = 30)
)

Then I use transition_reveal() from {gganimate} to make the animation:

ggplot(df, aes(x = x, y = y)) + 
  geom_path() +
  geom_polygon(aes(alpha = alpha), fill = 'grey30') +
  coord_fixed() +
  scale_alpha_identity() +
  transition_reveal(time)

Which yields the following animation:

gif that draws a circle

The circle is drawn sequentially (which is what I want), but the colour of the polygon does not change. It appears that only the first value of df$alpha is used for the whole animation.

My question is thus how can I change this animation such that the circle is still drawn sequentially AND the colour of the polygon gradually becomes greyer?


Solution

  • There may be an easier way to do this, but with a bit of data manipulation you can do it via transition_states:

    df$frame <- 1
    
    df <- do.call(rbind, lapply(seq(nrow(df)), function(i) {
      df$frame <- i
      df$alpha <- seq(0.1, 1, length = 30)[i]
      df[1:i,]
      }
    ))
    
    df <- df[df$frame > 2,]
    
    ggplot(df, aes(x = x, y = y)) + 
      geom_path() +
      geom_polygon(aes(alpha = alpha), fill = 'grey30') +
      coord_fixed() +
      scale_alpha_identity() +
      transition_states(frame)
    

    enter image description here