I would like to sample points from a normal distribution, and then build up a dotplot one by one using the gganimate
package until the final frame shows the full do
I think the key here is to imagine how you would create this animation manually, which is to say you would add dots one observation at a time to the resulting dotplot. With this in mind, the approach I used here was to create a ggplot
object that consisted of plot layers = number of observations, then step through layer by layer via transition_layer
.
# create the ggplot object
df <- data.frame(id=1:100, y=rnorm(100))
p <- ggplot(df, aes(y))
for (i in df$id) {
p <- p + geom_dotplot(data=df[1:i,])
}
# animation
anim <- p + transition_layers(keep_layers = FALSE) +
labs(title='Number of dots: {frame}')
animate(anim, end_pause = 20, nframes=120, fps=20)
Note that I set keep_layers=FALSE
to avoid overplotting. If you plot the initial ggplot
object, you'll see what I mean, since the first observation is plotted 100 times, the second 99 times... etc.
Since number of frames = number of observations, you need to adjust for scalability. Here, just keep the # frames constant, meaning you have to let the code group the frames into segments, which I am doing via the seq()
function, specifying length.out=100
. Note also in the new example, the dataset contains n=5000
. In order to keep the dotplot in frame, you need to make the sizes of the dots really tiny. I probably made the dots a bit too small here, but you ge the idea. Now the # frames = number of groups of observations.
df <- data.frame(id=1:5000, y=rnorm(5000))
p <- ggplot(df, aes(y))
for (i in seq(0,length(df$id), length.out=100)) {
p <- p + geom_dotplot(data=df[1:i,], dotsize=0.08)
}
anim <- p + transition_layers(keep_layers=FALSE) +
labs(title='Frame: {frame}')
animate(anim, end_pause=20, nframes=120, fps=20)