Search code examples
ranimationggplot2animated-gifgganimate

How to create an animation showing an array of ordered numbers with number line?


I have an array var1 of 94 numbers. I want them to be shown in a gif with defined interval (e.g. 0.05 seconds). If possible, I also want to add an number line. I expect to see a picture like this (animated, of course):

========================================================

COV1 = 2.34

----------|-------------------------------------> cov1

_____2.34

========================================================

I just succeeded in using the gganimate package for some plots but then I realized I also needed to animate something that are not plots... Maybe something related to the animation package?

Thanks!


Solution

  • It doesn't seem particularly enlightening (in fact it gives me a headache to look at it), but it's animated.

    library(tidyverse)
    library(gganimate)
    
    set.seed(10)
    dat = data.frame(x=sort(runif(94, 0, 100)))
    
    p = ggplot(dat) +
      geom_line(data=data.frame(y=rep(c(0.90,0.905,1.095,1.1),each=2), x=rep(range(dat$x), 4)), 
                aes(x,y,group=y), size=1, colour="grey40", linetype=2) +
      geom_line(aes(x,y=1), colour="grey60", size=1.5, linetype="11") +
      geom_text(aes(label=paste0("COV1\n", round(x,2)), x=x, y=1.05, frame=x), size=5) +
      geom_segment(aes(x=min(dat$x), xend=x, y=1, yend=1, frame=x), 
                   arrow=arrow(angle=90, length=unit(0.4, "cm")), size=1.5) +
      scale_y_continuous(limits=c(0.8,1.1)) +
      theme_void() +
      theme(plot.title=element_blank())
    
    gganimate(p, filename="my_gif.gif", interval=0.05)
    

    enter image description here