12.2 Animating normal PDFs

Sometimes when animating a normal PDF the curve can appear to bounce up and down, and can look incorrect. This animation shows how certain points move from frame to frame and helps explain why the “bouncing” happens.

Note that the points have fixed \(x\) coordinates, and the \(y\) coordinates change in each frame of the animation. The vertical lines show the paths of those points. The normal curve connecting the points appears to bounce up and down because of where the points are located while transitioning from frame to frame.

Code
library(tidyverse)
library(gganimate)
library(pubtheme)

x = rep(seq(-5, 5, by=.5))

df = data.frame(frame = rep(1:3, 
                            each = length(x)), 
                x = c(x,x,x), 
                y = c(dnorm(x, 0, 1), 
                      dnorm(x, 1, 1), 
                      dnorm(x, 2, 1)) %>% 
                  round(3), 
                id = x)
head(df)
tail(df)

df.prior = df %>% 
  filter(frame == 1) %>% 
  select(-frame)

g = ggplot(df, 
           aes(x = x, y = y))+
  geom_point(data  = df.prior, 
             color = 'gray')+
  geom_line (data  = df.prior, 
             color = 'gray')+
  geom_point(aes(color = as.factor(x)), 
             show.legend = F, 
             size = 4)+ 
  geom_line(show.legend = F)+
  geom_line(data = df %>% select(-frame), 
            aes(color = as.factor(x)), 
            show.legend = F)+
  scale_color_manual(values = rep(cb.pal, 
                                  length.out = length(x)))
  
g = g %>% 
  pub(xlim = c(-5, 5), 
      ylim = c(0, .5))

## check by plotting frames in different windows
g + 
  facet_wrap(~frame)

  frame    x     y   id
1     1 -5.0 0.000 -5.0
2     1 -4.5 0.000 -4.5
3     1 -4.0 0.000 -4.0
4     1 -3.5 0.001 -3.5
5     1 -3.0 0.004 -3.0
6     1 -2.5 0.018 -2.5
   frame   x     y  id
58     3 2.5 0.352 2.5
59     3 3.0 0.242 3.0
60     3 3.5 0.130 3.5
61     3 4.0 0.054 4.0
62     3 4.5 0.018 4.5
63     3 5.0 0.004 5.0
[1] 69.99122
[1] 80
[1] 20
[1] 169.9912
Code
## animate
# gg = g +
#   transition_states(frame,
#                     transition_length = 1,
#                     state_length      = 0,
#                     wrap = F) +
#   ease_aes('linear')
# 
# a = animate(gg, 
#             height = 1440/3*3/4, 
#             width  = 1440/3,
#             fps = 10,
#             duration = 4,
#             end_pause = 10)
# a
# anim_save(a, filename = 'img/normal-dist.gif')