This document shows an example how to create an easy animations with ggplot2, using the R package gganimate developed by David Robinson. The original poster was written by him here. This RMD document is a walking-through process of myself to save your time/efforts.
First, to install the gganimate package you need to install it from github using the command install_github in devtools library.
library(devtools)
install_github("dgrtwo/gganimate")
After that, you can load the necessary libraries
library(dplyr)
library(ggplot2)
library(broom)
library(gganimate)
Set the ggplot2 theme, set the random seed, initialize the data set.
theme_set(theme_bw())
set.seed(2016)
min_weight <- .0005
bws <- c(.25, .5, .75, 1)
x_data <- c(rnorm(30, 0), rnorm(15, 6))
Add some y noise to be visible
dat <- data_frame(x = x_data) %>%
mutate(y = rnorm(n(), .5, .025))
Get the density fits for different band-width, here using the inflate() function from the broom package, which is also a very neat package written by David Robinson. I highly recommend you to master it. The main purpose of broom package is to convert statistical analysis objects from R into tidy data frames, so that they can more easily be combined, reshaped and otherwise processed with tools like ‘dplyr’, ‘tidyr’ and ‘ggplot2’. The package provides three S3 generics: tidy, which summarizes a model’s statistical findings such as coefficients of a regression; augment, which adds columns to the original data such as predictions, residuals and cluster assignments; and glance, which provides a one-row summary of model-level statistics. Let’s tidy up a bit
fits <- dat %>%
inflate(bw = bws) %>%
do(tidy(density(.$x, bw = .$bw[1], from = -4, to = 9, n = 100)))
centers <- sort(unique(fits$x))
Then calculate weights at each x0 center
prep <- dat %>%
inflate(center = centers, bw = bws) %>%
mutate(weight = dnorm(x, center, bw)) %>%
filter(weight > min_weight)
Raster data for the background
ras <- expand.grid(x = seq(min(centers), max(centers), .05),
y = c(0, 1)) %>%
inflate(center = centers, bw = bws) %>%
mutate(weight = dnorm(x, center, bw)) %>%
filter(weight > min_weight)
Finally, create the plot with layers for the background, the points, the red fills, the red vertical line, and the cumulative line plot.
p <- ggplot(prep, aes(x, y)) +
geom_raster(aes(alpha = weight, frame = center), data = ras, fill = "gray", hjust = 0, vjust = 0) +
geom_point(shape = 1, size = 3, data = dat, alpha = .25) +
geom_point(aes(alpha = weight, frame = center), color = "red", size = 3) +
geom_vline(aes(xintercept = x, frame = x), data = fits, lty = 2, color = "red") +
geom_line(aes(frame = x, cumulative = TRUE), color = "red", data = fits) +
coord_cartesian(ylim = c(0, max(prep$y))) +
facet_wrap(~bw) +
ylab("")
To show the animate plot in the RMD knitr document, put the fig.show=“animate” in option. At the beginning, I have difficulty to render the plots, after researching, I found that you need FFmpeg to create a WebM video to play in the HTML page. You need to install the FFmpeg and add the path in your system, then your are ‘ALL SET’.
NOTE: It still shows “Error: Unsupported video type or invalid file path” in IE 10.0, no problem in Chrome. I do not know why :(
gg_animate(p, interval = .1, title_frame = FALSE)
To save your animate as a GIF file, you need to download and install Imagemagick, and also, most importantly, you need run you R-Studio as an administrator, otherwise, you will get error message, :(.
setwd("path\to\save\GIF")
g <- gg_animate(p, interval = .1, title_frame = FALSE, "filename.gif")
Last, my session information
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] gapminder_0.2.0 gganimate_0.1 broom_0.4.0 ggplot2_2.0.0 dplyr_0.4.3
loaded via a namespace (and not attached):
[1] Rcpp_0.12.3 knitr_1.11 magrittr_1.5 mnormt_1.5-3 munsell_0.4.2
[6] colorspace_1.2-6 lattice_0.20-33 R6_2.1.1 stringr_1.0.0 plyr_1.8.3
[11] tools_3.2.2 parallel_3.2.2 grid_3.2.2 gtable_0.1.2 nlme_3.1-122
[16] psych_1.5.8 DBI_0.3.1 htmltools_0.2.6 yaml_2.1.13 lazyeval_0.1.10
[21] assertthat_0.1 digest_0.6.9 reshape2_1.4.1 tidyr_0.3.1 rsconnect_0.4.1.4
[26] rmarkdown_0.9 animation_2.4 labeling_0.3 stringi_1.0-1 scales_0.3.0