Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gganimate barchart: smooth transition when bar is replaced

I want to create an animated barplot with the gganimate package. The barplot should contain 4 bars, but only three of the bars should be shown at the same time. When a bar drops out and a new bar comes in, the animation should be smooth (as it is when two bars switch position within the plot).

Consider the following example:

# Set seed
set.seed(642)

# Create example data
df <- data.frame(ordering = c(rep(1:3, 2), 3:1, rep(1:3, 2)),
                 year = factor(sort(rep(2001:2005, 3))),
                 value = round(runif(15, 0, 100)),
                 group = c(letters[sample(1:4, 3)],
                           letters[sample(1:4, 3)],
                           letters[sample(1:4, 3)],
                           letters[sample(1:4, 3)],
                           letters[sample(1:4, 3)]))

# Load packages
library("gganimate")
library("ggplot2")

# Create animated ggplot
ggp <- ggplot(df, aes(x = ordering, y = value)) +
  geom_bar(stat = "identity", aes(fill = group)) +
  transition_states(year, transition_length = 2, state_length = 0)
ggp

enter image description here

If a bar is exchanged, the color of the bar just changes without any smooth animation (i.e. the new bar should fly in from the side and the replaced bar should fly out).

Question: How could I smoothen the replacement of bars?

like image 457
Joachim Schork Avatar asked Feb 12 '19 18:02

Joachim Schork


1 Answers

I'm getting a little glitch at 2003 (b and c seem to swap upon transition), but hopefully this helps you get closer. I think enter_drift and exit_drift are what you're looking for.

library("gganimate")
library("ggplot2")
ggp <- ggplot(df, aes(x = ordering, y = value, group = group)) +
  geom_bar(stat = "identity", aes(fill = group)) +
  transition_states(year, transition_length = 2, state_length = 0) + 
  ease_aes('quadratic-in-out') +   # Optional, I used to see settled states clearer
  enter_drift(x_mod = -1) + exit_drift(x_mod = 1) +
  labs(title = "Year {closest_state}")
animate(ggp, width = 600, height = 300, fps = 20)

enter image description here

like image 71
Jon Spring Avatar answered Oct 03 '22 04:10

Jon Spring