Animating a bar plot.

Here we will have a quick overview of how you can quickly produce gif animated graphics in R. Gif is a very cool way of visualizing data. What do I need to do to produce gif? First load the packages we need. If you don’t have these packages install them. NB: The gganimate package was developed for R version 3 5 2 or lower. You may have problems if you are working with R version 3 5 3. This is written in R version 3 6 0.

Load the packages and prepare the data. For this blogpost we need dplyr, ggplot2, gganimate and scales package

library(dplyr) # for data manipulation 
library(ggplot2) # for plotting 
library(gganimate) #for animating your plot
library(scales) # for scaling your x or y-axis 

The data is downloaded from PubMed and it is to compare publication outputs of three universities over time

Merge the three data frames and create one data frame.

merged <- rbind(uog, addis, jimma)

pubdata <- merged[which(merged$year <2019) , ]
pubdata$pubyear <- as.factor(pubdata$year)

Write the ggplotcode and asign it to pub

pub <- ggplot(pubdata, aes(x=year,y=count,fill=university)) + 
                geom_bar(stat="identity", width=1, position=position_dodge()) +
                transition_time(year) + shadow_mark() + 
                scale_x_continuous(limits=c(2000,2019)) +
                xlab("Year") + ylab("Publication") +
                theme(axis.text = element_text(size=12),
                      axis.title = element_text(size=14, face="bold"))

###Pass the ggplot object on gganimate

animate(pub, width = 800, height = 600, duration = 5)

*There are a lot more you can do with gganimate. Google for more!

References

  1. https://github.com/thomasp85/gganimate#old-api
  2. https://paldhous.github.io/ucb/2018/dataviz/week14.html

Contact

Twitter https://twitter.com/MihiretuKebede1