I have this code producing this plot:
library(ggplot2)
time_points <- rep(1:10, times = 5)
class <- rep(letters[1:5], each = 10)
# Set different means for each class
class_means <- c(0, 5, 10, 20, 30)
outcome_values <- rnorm(50, mean = rep(class_means, each = 10), sd = 1)
# Create dataframe
df <- data.frame(
time = time_points,
class = class,
outcome = outcome_values
)
ggplot(df) +
geom_line(aes(x = time_points, colour = class, y = outcome))
I want to use gganimate
to create an animation in which the lines 'converge' towards one of them. It could be the mean, or, in this simple plot, I would like the lines from classes a,b,d and e to 'slide' towards c. When they reach c, all other lines disappear. My idea would to be to use this to animate how different lines converge to one other line, which for my case in mind would be the mean.
Is this even possible with gganimate?
Thanks!
library(gganimate); library(tidyverse)
df |>
crossing(t = seq(0, 1, length.out = 100)) |>
mutate(outcome2 = (1-t)*outcome + t*outcome[class == "c"], .by = time) |>
ggplot() +
geom_line(aes(x = time, colour = class, y = outcome2)) +
transition_time(t)
Or just for curiosity:
df |>
crossing(t = seq(0, 1, length.out = 2)) |>
mutate(outcome2 = (1-t)*outcome + t*outcome[class == "c"], .by = time) |>
ggplot() +
geom_line(aes(x = time, colour = class, y = outcome2)) +
transition_states(t) +
ease_aes("bounce-out")