Search code examples
rgganimate

Using tweenr and gganimate with bar plots


How do I use tweenr along with gganimate to create a very smooth animation between the two bar charts below?

library(tweenr)
library(gganimate)
library(tidyverse)

df <- tibble(
  decile = c("lowest", "second", "third", "lowest", "second", "third"),
  change = c(1, 2, -0.5, -2, -3, 4),
  year = c(2001L, 2001L, 2001L, 2002L, 2002L, 2002L)
)

df2001 <- filter(df, year == 2001)
df2002 <- filter(df, year == 2002)

ggplot(df2001, aes(x = decile, y = change)) +
  geom_col() +
  scale_y_continuous(limits = c(-5, 5)) +
  theme_minimal()

ggplot(df2002, aes(x = decile, y = change)) +
  geom_col() +
  scale_y_continuous(limits = c(-5, 5)) +
  theme_minimal()

Solution

  • Edit: changed transition_states and ease_aes to spend more time on transition, increased font size, and changed animate terms to make duration longer & movement slower.

    a <- ggplot(df, aes(x = decile, y = change/2, 
                        height = change, width = 0.9, group = decile)) +
      geom_tile() +
      scale_y_continuous(limits = c(-5, 5), name = "change") +
      theme_minimal(base_size = 16) +
      transition_states(year, wrap = T, transition_length = 10, state_length = 1) +
      ease_aes("cubic-in-out")
    
    animate(a, fps = 30, duration = 10, width = 500, height = 300)
    # Use up to two of fps, nframes, and duration to define the
    #   length and frame rate of the animation.
    

    enter image description here


    Please note, I used geom_tile above because geom_col produced this unconventional behavior upon transition. I suspect the drawn geom_col doesn't distinguish between its baseline and its extent, but rather between its min and max, resulting in "sliding" animation. (Curious if others see an easier workaround.)

    a <- ggplot(df, aes(x = decile, y = change)) +
      geom_col() +
      ...
    

    enter image description here