Wednesday, December 9, 2020

Line Chart Animation in R

R is a powerful software environment for dealing with graphics. In this post, I illustrate the use of R for producing line chart animation. I will use Nepal Stock exchange data with 2205 daily observations.

The data and R script can be downloaded from here.

# It uses the following packages in R 

library(ggplot2)
library(lubridate)
library(dplyr)
library(gganimate)
library(tidyr)

 # First set the working directory 

 setwd("C:/Users/siddhabhatta/Desktop/October31")
# read the data by using the 'readxl' package.

library(readxl)
nepse=read_excel('nepse.xlsx')

head(nepse)

# save date as standard date format
nepse$new_date<-as.Date(nepse$date, format="%m/%d/%y")
head(nepse$new_date)
summary(nepse)

# produce a static line plot
ggplot(data=nepse, aes(x=new_date, y=close))+
  geom_line(color="blue",  size=1.0)+
  theme_classic()+
  ggtitle("Nepse Index Movement in Nepal")

# add aesthetics and labels to the plot  and save it as an object (p here) 
p<-nepse %>%
  ggplot(aes(x=new_date, y=close))+
  geom_line(color="blue",  size=1.0)+
  geom_point(size=5, color="green")+
  geom_text(aes(label=new_date),color="darkblue", fontface="bold", vjust=-2)+
  geom_text(aes(label=close),color="red",fontface="bold", vjust=-4)+
  theme_classic()+
  theme(plot.title = element_text(hjust = 0.5))+
  ggtitle("NEPSE Index Movement of the Past 2205 Days")+

  transition_reveal(new_date) # this last line produces the animation by date
animate(p, fps=2, nframes=500, width=1200) # number of frames 500 and frame per second is 2

# you can save the animation in gif format by usng the following line of codes
p1<-animate(p, nframes=500,  fps = 2,  width = 1200,
        renderer = gifski_renderer())
anim_save("animation.gif", animation = p1 )

Here is the output.

Here is the video explanation in my YouTube Channel.


 



No comments: