Reputation: 2147
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
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?
Upvotes: 5
Views: 2176
Reputation: 66765
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)
Upvotes: 6