Search code examples
rggplot2gganimate

How can I make gganimate animate a column chart by starting at zero as specified in the dataset


I am producing an animated column chart using gganimate. See below for the example code. The problem is that in the example, company A makes zero profit in 2018 and makes a loss of -2 in 2019. I would expect the animation for company A to start at zero and to go to -2, however it starts at 5 which is the profit for company B in 2018.

Can anyone amend the code so that for company A the animation starts at zero rather than 5?

 library(ggplot2)
 library(gganimate)
 year<-c(2018,2018,2019,2019,2020,2020)
 country<-c("USA","USA","USA","USA","USA","USA")
 company<-c("A","B","A","B","A","B")
 profit<-c(0,5,-2,2,0,0)
 df<-data.frame(year,country,company,profit,stringsAsFactors = FALSE)

 ggplot(data = df, aes(x = country, y = profit,fill=company)) +
 geom_bar(position = "stack", stat ='identity')+
 transition_states(
 year,
 transition_length = 2,
 state_length = 1,wrap=FALSE
 )+
 ggtitle('Year: {closest_state}')+
 ease_aes('sine-in-out') 

enter image description here


Solution

  • By changing position="stack" to position="identity" solved this. What was happening was that the 0 from company A in 2018 was being stacked on top of the 5 of company B in 2018. This meant that when it started animating the starting point for company A was 5.

     library(ggplot2)
     library(gganimate)
     year<-c(2018,2018,2019,2019,2020,2020)
     country<-c("USA","USA","USA","USA","USA","USA")
     company<-c("A","B","A","B","A","B")
     profit<-c(0,5,-2,2,0,0)
     df<-data.frame(year,country,company,profit,stringsAsFactors = FALSE)
    
    ggplot(data = df, aes(x = country, y = profit,fill=company)) +
    geom_bar(position = "identity", stat ='identity')+
    transition_states(
    year,
    transition_length = 2,
    state_length = 1,wrap=FALSE
    )+
    ggtitle('Year: {closest_state}')+
    ease_aes('sine-in-out')