2

I am trying to add a line to my animation, but I couldn't make it work using the concept of frame. This is a reproducible example:

df <- read.table(header = TRUE, text = 'key   value   bins    maxIntensity
A      4     0    1
A      1     1    1
A      0     2    1
B      3     0    2
B      2     1    2
B      5     2    2
D      2     0    1
D      3     1    1
D      0     2    1')

the animation can be created using gganimate package:

library('animation')
library('gganimate')

par(bg = "white") 
g <- ggplot(df, aes(xmin = df$bins, xmax = df$bins + 1, ymin = 0, ymax = df$value, frame = df$key))
g <- g + geom_rect(fill=alpha("Orange", alpha = 1))
g <- g + labs(title = "Test Histogram")
g <- g + scale_y_continuous(labels = scales::comma)
gganimate(g, ani.width=400, ani.height=400, interval = .4, "test.gif")

Which works just fine.

Now I would like to add a line, at a different location for each frame. The location is specified in df$maxIntensity. So, I think I should add this:

g <- g + geom_vline(xintercept = df$maxIntensity, lty=3, color = "black")

but that simply adds all the lines at once, at each frame. Any idea how add one line to each frame?

enter image description here

Azim
  • 1,596
  • 18
  • 34

1 Answers1

3

Making a reproducible example made me have a much faster code on which I could try a plenty of different options. (My original code would take ~10 minutes to show me any results.) So, the key is to add frame again to geom_vline:

g <- g + geom_vline(aes(xintercept = df$maxIntensity,  frame = df$key))

So, the code would look like:

par(bg = "white") 
g <- ggplot(df, aes(xmin = df$bins, xmax = df$bins + 1, ymin = 0, ymax = df$value, frame = df$key))
g <- g + geom_rect(fill=alpha("Orange", alpha = 1))
g <- g + geom_vline(aes(xintercept = df$maxIntensity,  frame = df$key), lty=2, size = 1, color = "black")
g <- g + labs(title = "Test Histogram")
g <- g + scale_y_continuous(labels = scales::comma)
gganimate(g, ani.width=400, ani.height=400, interval = .4, "test.gif")

enter image description here

Azim
  • 1,596
  • 18
  • 34
  • 2
    Behold the power of a reproducible example (I was going to post the same solution, just took me a while to install everything on Windows). Also, you should probably avoid using "$" in your aes() commands. Those aren't necessary and can lead to trouble in some cases. Because you pass `df` to `ggplot()`, by default all variables will be looked up in that data.frame first. – MrFlick Mar 14 '18 at 20:07
  • 3
    `frame` is deprecated from `gganimate`. So this solution is not valid anymore. – M-- Jun 09 '19 at 03:45