0

I am trying to animate a stacked bar chart over time. In particular, I would like each stack to first build up in a given year and then transition to the next year. Also, I would like to make sure the past bars are visible. The following code plots each bar at once and transitions to the next year while making the previous years invisible. Is there a way to solve this issue?

library(tidyr)  
library(ggplot2)
library(gganimate)
library(dplyr)

df <- data.frame(stringsAsFactors=FALSE,
                 Year = c("2010", "2011", "2012"),
                 LabelOne = c(1000, 1500, 2000),
                 LabelTwo = c(50, 100, 150),
                 LabelThree = c(20, 30, 40)
)

df_long <- gather(df, lbs, Value, LabelOne:LabelThree, -Year)
head(df_long)

pp <- ggplot(df_long, aes(Year, Value)) +
  geom_bar(stat = "identity", aes(fill = lbs)) +
  transition_states(Year, 
          transition_length = 4, state_length = 2) +
    ease_aes('cubic-in-out')

animate(pp, nframes = 300, fps = 50, width = 400, height = 550)
Marco Sandri
  • 23,289
  • 7
  • 54
  • 58
Ercan
  • 1

1 Answers1

0

If you make your data look like this:

df2 <- structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), Year = c(2010L, 2010L, 2010L, 
2010L, 2010L, 2010L, 2011L, 2011L, 2011L, 2010L, 2010L, 2010L, 
2011L, 2011L, 2011L, 2012L, 2012L, 2012L), lbs = structure(c(1L, 
3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 
2L), .Label = c("LabelOne", "LabelThree", "LabelTwo"), class = "factor"), 
    Value = c(1000L, 50L, 20L, 1000L, 50L, 20L, 1500L, 100L, 
    30L, 1000L, 50L, 20L, 1500L, 100L, 30L, 2000L, 150L, 40L)), class = "data.frame", row.names = c(NA, 
-18L))

You can animate over ID instead of Year and it builds sequentially. Group 1 is 2010, group 2 is 2010 and 2011, and group 3 is 2010, 2011, and 2012

pp <- ggplot(df2, aes(Year, Value)) +
  geom_bar(stat = "identity", aes(fill = lbs)) +
  transition_states(ID, 
          transition_length = 4, state_length = 2) +
    ease_aes('cubic-in-out')
Mako212
  • 6,787
  • 1
  • 18
  • 37
  • Thnx much. Great solution. A minor issue, though. I would like the values to stack up sequentially for each year, then transition to the next year. As is, the code plots the stacked bar all at once, for a given year and then moves to the next year. Is it possible to solve this issue? thnx. – Ercan Jan 05 '19 at 13:24