Sunday, May 30, 2021

Bar Chart Animation with R

In this blog, I illustrate about how we can build bar chart race in R that is used to visualize the evolution of a variable over time. I will show the evolution of public debt in top 25 countries in the world over the period of 2007 to 2020. The dataset has been taken from IMF WEO 2021 (April) database available here.   

The dataset as well as the R script files are available here

The first step is to import the dataset in R.

rm(list=ls())
setwd("C:/Users/SIDDHARAJ BHATTA/Desktop/R for Data Analysis")
debt <- read.csv("debt.csv")

In the second step, we convert the data from wide to long format by using the tidyr package.

library(tidyr)
names(debt)<-as.character(2003:2020)
debt_long <- gather(data=debt, key=Year, value=debt, 4:18, factor_key=TRUE)
debt_long$Year <- as.numeric(as.character(debt_long$Year))
debt_long$country<-debt_long$`2005`

In the third step, we rank the countries according to debt GDP ratio and filter the top 25 countries using dplyr package.

library(dplyr)
names(debt_long)
data<-debt_long %>%
  group_by(Year) %>%
  arrange(Year, -debt) %>%
  mutate(rank = 1:n()) %>%
  filter(rank <= 25)

 We will use ggplot2 and ggnimate package to plot the bar chart and animate it.

library(ggplot2)
library(gganimate)

data %>%  
  ggplot() +  
  aes(xmin = 0 ,  
      xmax = debt) +  
  aes(ymin=rank-0.45,
      ymax=rank+0.45,
      y = rank) +  
  facet_wrap(~ Year) +  
  geom_rect(alpha = .7, fill="darkblue") +  
  scale_x_continuous(  
    limits = c(0, 500),  
    breaks = c(0, 100, 300, 500)) +  
  geom_text(col = "darkblue",  
            hjust = "right",  
            aes(label = country),  
            x = -50, size=6) +  
  scale_y_reverse() +  
  labs(fill = NULL) +  
  labs(x = 'Debt GDP Ratio') +  
  labs(y = "") +
  theme_classic()->  
  my_plot

plot<-my_plot +
  theme_classic()+
  facet_null() +  
  scale_x_continuous(  
    limits = c(-500, 600),  
    breaks = c(0, 200, 400, 600)) +  
  geom_text(x = 500 , y = -2,  
            family = "Times",  
            aes(label = as.character(Year)),  
            size = 14, col = "darkblue") +
  geom_text(col = "white",  
            hjust = "right",  
            aes(label = debt),  
            x = 80, size=5) +
  ggtitle("Outstanding Public Debt  as percent of GDP")+
  xlab("Debt GDP Ratio")+
  ylab("Top 25 Countries")+
  theme(
    panel.background = element_rect(fill='lightblue', size=0.5,
                                    linetype=0, colour='lightblue'),
    plot.title = element_text(color="red", size=16, hjust=0.5, face="bold.italic"),
    axis.title.x = element_text(color="darkblue", size=13, face="bold"),
    axis.title.y = element_text(color="darkblue", size=13, face="bold")
  ) +
    gganimate::transition_time(Year)

animate(plot, nframes=14, fps=1, width=800)
 

The following lines of codes produce the Output in GIF Format. 

p1<-animate(plot, nframes=14,  fps = 1,  width = 800,
            renderer = gifski_renderer())

anim_save("animation.gif", animation = p1 )

The video explanation of this process is available here. 

I can be reached at siddhabhatta@gmail.com.


No comments: