Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Animated bar graphs in R. How a simple animation can (maybe) contribute to a better understanding of data
# 1. step: Load all packages we need ----------------------------------------------------------------------------
library(data.table) #order/add/modify/delete data
library(gganimate) #create easy animations with ggplot2
library(RColorBrewer) #Provides color schemes
library(ggplot2) #A system for 'declaratively' creating graphics
# 2. step: Toy example ------------------------------------------------------------------------------------------
#toy example data
dt = data.table(time=1:10, x=round(runif(10, 50, 100), 0))
#number of frames per bar during animation
n_frames_per_bar = 33
#split dataset (e.g. every sample displayed on x-axis)
split_dt = split(dt, dt$time)
#split every sample (from 1 to maximum, in n_frames_per_bar steps)
split_dt_fill = lapply(split_dt, function(dti) {
data.table(time=dti$time, x=seq(1, dti$x, by = max(dt$x)/n_frames_per_bar))
})
#every sample now has the same number of datapoints (absent datapoints are filled with max.value)
split_dt_fill2 <- lapply(split_dt_fill, function(dti){
if (nrow(dti) < n_frames_per_bar){
add_table <- data.table(time = dti$time[1], x = max(dti$x))
dti <- rbind(dti, as.data.frame(lapply(add_table,function(x)rep(x,n_frames_per_bar - nrow(dti)))))
}
else{
dti <- dti
}
})
#bin together all the different samples (or 'time' points)
dt_fill = rbindlist(split_dt_fill2)
#id each row as its own frame for every 'time' | add column 'frame'
dt_fill[,frame := rep(1:n_frames_per_bar,10)]
#plot using ggplot2 (gganimate's frame arg in aes)
p = ggplot(dt_fill, aes(x=time, y=x, frame=frame, fill = x)) +
geom_bar(stat="identity", position = "identity") +
guides(fill=FALSE) +
scale_fill_gradientn(colours = brewer.pal(9, "Blues")) +
labs(x="Time", y="Value", title="")
#create gif (using interval to specify the time per frame)
gganimate(p, title_frame = FALSE, interval = .001)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.