Search code examples
rggplot2animationplotgganimate

gganimation: animate bars one by one and retatin previously shown


I wonder how to animate geom_bar from ggplot2 with gganimate in such a way that previously shown bar stay and next come.

library(ggplot2)
library(gganimate)
 
a <- data.frame(group=c("A","B","C"), values=c(3,2,4), frame=rep('a',3))
b <- data.frame(group=c("A","B","C"), values=c(5,3,7), frame=rep('b',3))
df1 <- rbind(a,b)  
 
Plot1 <-
  ggplot(data= df1, aes(x = group, y = values, fill = group)) + 
  geom_bar(stat='identity') +
  theme_bw() +
  transition_states(
    states            = group
  , transition_length = 2
  , state_length      = 1
  ) 
Plot1

The above given code shows bar one by one but fade the previously shown. However, I want to retain already shown bars. Any thoughts.


Solution

  • Check out ?shadow_mark() from the gganimate package. I think this achieves what you are looking to accomplish:

    library(ggplot2)
    library(gganimate)
    
    a <- data.frame(group=c("A","B","C"), values=c(3,2,4), frame=rep('a',3))
    b <- data.frame(group=c("A","B","C"), values=c(5,3,7), frame=rep('b',3))
    df1 <- rbind(a,b)  
    
    Plot1 <-
      ggplot(data= df1, aes(x = group, y = values, fill = group)) + 
      geom_bar(stat='identity') +
      theme_bw() +
      transition_states(
        states            = group
        , transition_length = 2
        , state_length      = 1
      ) +
      shadow_mark() # keeps past data displayed
    Plot1