Home > Back-end >  How to create animated curves with ggplot2
How to create animated curves with ggplot2

Time:07-28

I'm trying to replicate the effect of this animation with ggplot2 and gganimate enter image description here

I've managed to accomplish a similar transition but the problem is that the animation of the curve doesn't start at 0.

data <- data.frame(observation = c("a", "b", "c"),
          start = 0,
          y = 0,
          end = c(10, 20, 30))        



ggplot(data)  
  geom_curve(aes(x = start, xend = end, y = 0, yend = 0), curvature = -.5, color = "yellow")  
  transition_states(observation)  
  theme_void()  
  theme(
    plot.background = element_rect(fill = "black", color = "black"),
    panel.background = element_rect(fill = "black", color = "black")
    )

enter image description here

Thanks in advance,

CodePudding user response:

You will get more control if you use geom_path and specify the curves yourself. Just reveal them with transition_reveal

library(gganimate)

data <- data.frame(time = rep(1:100, 2),
                   x = c(1:100, 1:50, rep(50, 50)),
                   y = c(sin(seq(pi/4, 3*pi/4, length = 100)),
                         sin(seq(pi/4, 0.5 * pi, length = 50)), rep(1, 50)),
                   col = rep(c("gray", "yellow"), each = 100))   

p <- ggplot(data, aes(x, y, color = col))  
  geom_path()  
  transition_reveal(data$time)  
  theme_void()  
  scale_color_identity()  
  theme(
    plot.background = element_rect(fill = "black", color = "black"),
    panel.background = element_rect(fill = "black", color = "black")
    )

anim_save("anim.gif", p, nframes = 100, fps = 30, width = 650, height = 200,
           device = "ragg_png")

anim.gif

enter image description here

  • Related