6

Using R, I am trying to make a line graph which is revealed left to right based on x-axis using gganimate. I have managed to do this but what I also wanted to do was make it so that the scale_x_continuous(limits = c(i-5,i+5)), i.e. there is a window around the point that is being revealed and the window will move along while the next point is being revealed.

I have tried many ways to get this including implementing some sort of loop in scale_x_continuous with and without aes(). Nothing seems to work. I am quite new with ggplot2 and especially with gganimate but I couldn't find any help online. I have a feeling the answer is probably quite simple and I just missed it.

Sort of like this but with gganimate:

Similar example but not with gganimate

The following is some reproducible code to show you roughly what I've done so far.

library(ggplot2)
library(gganimate)
library(gifski)
library(png)


Step  <- c(1:50,1:50)
Name  <- c(rep("A",50), rep("B",50))
Value <- c(runif(50,0,10), runif(50,10,20))
Final <- data.frame(Step, Name, Value)

a <- ggplot(Final, aes(x = Step, y = Value, group = Name, color = factor(Name))) + 
 geom_line(size=1) + 
 geom_point(size = 2) + 
 transition_reveal(Step) + 
 coord_cartesian(clip = 'off') + 
 theme_minimal() +
 theme(plot.margin = margin(5.5, 40, 5.5, 5.5)) +
 theme(legend.position = "none") 

options(gganimate.dev_args = list(width = 7, height = 6, units = 'in', res=100))
animate(a, nframes = 100)
tjebo
  • 21,977
  • 7
  • 58
  • 94
user3456588
  • 609
  • 4
  • 9

1 Answers1

5

Don't use a transition, use a view. E.g.:

ggplot(Final, aes(x = Step, y = Value, color = factor(Name))) + 
    geom_line(size = 1) + 
    geom_point() +
    view_zoom_manual(
        0, 1, pause_first = FALSE, ease = 'linear', wrap = FALSE,
        xmin = 1:40, xmax = 11:50, ymin = min(Final$Value), ymax = max(Final$Value)
    ) +
    scale_x_continuous(breaks = seq(0, 50, 2))

enter image description here

Axeman
  • 32,068
  • 8
  • 81
  • 94
  • Thanks for your help. One more thing I was confused about, I notice this graph will be jittery. I have names moving around in my future work and they are shaking on their spot. It looks ugly. Do you know how to smoothly move from span to span instead of just jumping? – user3456588 Jun 20 '19 at 10:46
  • 1
    Well what I'm doing is mixing transition_reveal with view. What I want is a slowly revealing line graph as shown above but with the x-axis view following as you have done. In your example they are not being revealed. But the reveal is often in 1 of 2 frames osculating between. Now I have to try and find a way for this osculation not to happen. I feel trying to calculate the exact number of frames needed to stop osculation is long winded and that there must be an easier way. I suppose something like this is what I'm after: https://www.youtube.com/watch?v=B1ISzIJkjwg – user3456588 Jun 20 '19 at 16:12