We all love ggplot2! It is one of the most widely used R packages for data visualisations. But why restrict oneself just to static plots? Let’s see how we can create animated ggplot objects in R.
In order to create and display animations in R, you must first download an external software ImageMagick STL. http://www.imagemagick.org/script/download.php#windows
Install the latest version compatible with your computer’s specifications. A very important note: At the time of installing, while ‘selecting additional tasks’ ensure you check the box “Install legacy utilities (e.g. convert)”. Once the installation is over, restart your computer.
Package "gganimate"
wraps the animation package to create animated ggplot2 objects. It is available on github and can be installed as follows: (Make sure you have package "devtools"
installed.)
Don’t forget to load package ggplot2
.
devtools::install_github("dgrtwo/gganimate")
library(ggplot2)
library(gganimate)
jobdata <- read.csv("Job Data.csv")
head(jobdata)
empno aptitude testofen tech_ g_k_ job_prof function. year
1 1 86 110 100 87 88 Marketing 2015
2 2 62 62 99 100 80 IT 2016
3 3 110 107 103 103 96 Finance 2015
4 4 101 117 93 95 76 IT 2016
5 5 100 101 95 88 80 Finance 2015
6 6 78 85 95 84 73 Finance 2016
Now let’s make an animated bubble plot:
theme_set(theme_grey())
plot<-ggplot(jobdata,
aes(aptitude, tech_, size = job_prof, color = function.,
frame = year))+
geom_point()+
labs(x="Aptitude",y="Technical")
ggplot()
initialises a new ggplot object.
geom_point()
creates a scatterplot.
size=
and color=
in aesthetics are used to create a bubble chart.
frame=
forms the core of this exercise. It is treated as another aesthetic. It creates additional layer in the ggplot()
object which is used as the animation variable.
gganimate(plot)
gganimate()
creates an animation plot.
gganimate()
object can be embedded in RMarkdown documents and it can even be saved as a gif file. Animated images are useful when we want to show graphs across multiple years / factor variables.