MYaseen208
MYaseen208

Reputation: 23908

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.

Upvotes: 0

Views: 248

Answers (1)

BDuff
BDuff

Reputation: 46

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

Upvotes: 2

Related Questions