Animating bar graphs

Data Science

Here we will have a quick look on how to create Gif or animated bar plots

Mihiretu Kebede
2020-07-13

Hello, this is my first ever blog post. Detail explanations of this data vizualization and other upcoming blogs are coming soon! Stay tuned.

#Set working directory
#setwd("F:/github/githubwebsite")

library(readxl)
mystepcount <- read_excel("F:/github/githubwebsite/mystepcount.xlsx")

str(mystepcount)
tibble [8 x 4] (S3: tbl_df/tbl/data.frame)
 $ Date       : chr [1:8] "Sept_14" "Sept_15" "Sept_16" "Sept_17" ...
 $ September  : num [1:8] 14 15 16 17 18 19 20 21
 $ Steps      : num [1:8] 1907 18767 10438 23128 28300 ...
 $ Killometres: num [1:8] 1.1 12.8 7.4 17.1 19.1 12.9 13.7 4.9
library(ggplot2)
library(gganimate)
library(scales)
theme_set(theme_bw())

mystepcount$September <- as.character(mystepcount$September)
#Plot step counts on the y-axis and days of September on the x-axis
ggplot(mystepcount, aes(x=September,y=Steps)) + 
  geom_bar(fill="darkturquoise", stat="identity", width=1, position=position_dodge()) + 
    geom_hline(yintercept = 10000, col="black", size=1)

animate(
  ggplot(mystepcount, aes(x=September,y=Steps)) + 
  geom_bar(fill="darkturquoise", stat="identity", width=1, position=position_dodge()) + 
    geom_hline(yintercept = 10000, col="black", size=1) +
  transition_states(September, wrap = FALSE) +
  shadow_mark() +
  enter_grow() +
  enter_fade() + 
  theme(axis.text = element_text(size=16),
        axis.title = element_text(size=16, face="bold")) + 
  xlab("September") +  
  scale_y_discrete(name="Step counts", limits=factor(c(5000,10000, 15000, 20000, 25000, 30000))) +
  theme(axis.line = element_line(colour = "black"),
          panel.border = element_blank()) ,
  
  duration = 5
  )

Contact

Please mention MihiretuKebede1 if you tweet this post.

Citation

For attribution, please cite this work as

Kebede (2020, July 13). Aspire Data Solutions: Animating bar graphs. Retrieved from http://www.mihiretukebede.com/posts/2020-07-13-Animating-bar-graphs_files/

BibTeX citation

@misc{kebede2020animating,
  author = {Kebede, Mihiretu},
  title = {Aspire Data Solutions: Animating bar graphs},
  url = {http://www.mihiretukebede.com/posts/2020-07-13-Animating-bar-graphs_files/},
  year = {2020}
}