DataScience+ An online community for showcasing R & Python tutorials. It operates as a networking platform for data scientists to promote their talent and get hired. Our mission is to empower data scientists by bridging the gap between talent and opportunity.
Programming

Making a Shiny dashboard using ‘highcharter’ – Analyzing Inflation Rates

Shiny is an amazing R package which lets the R developers and users build amazing web apps using R itself. It lets the R users analyze, visualize and deploy their machine learning models directly in the form of the web app. This package lets you host standalone apps on a webpage or embed them in R markdown documents or build dashboards and various forecasting applications. You can also extend your Shiny apps with CSS themes, htmlwidgets, and JavaScript actions. Shiny lets us write client-side front-end code in R itself and also lets users write server-side script in R itself. More details on this package can be found here.

I recently learned Shiny and started developing a web application using it.And since then I have been in love with it and have been using it in each and every data science and analytics project. The syntax is super easy to understand and there are lots of amazing articles and documentation available for you to learn it and use it. I personally had a background of developing full-stack web applications using HTML, CSS and javascript and other JS based scripting languages so I found the syntax easy.

This article is meant for people who at least have a basic understanding of how to use shiny in R or who either have knowledge of developing web apps. But still, it is easy for an intermediate level or beginner R user to learn shiny and its syntax to develop web apps.

In this article I am going to demonstrate how to make a dashboard using shinydashboard package. Shiny Dashboard is also another package similar to shiny which is specifically used to make dashboards easily in R and deploy them. More details on this package can be found here.

Secondly, in this article I am going to demonstrate how to use highcharter package which is a Javascript based visualization library in R to develop amazing and beautiful plots. Its syntax is somewhat similar to qplot function from the ggplot2 package in R. So if you have good experience of using ggplot2 package then you would find it easier to use. Details about the highcharter can be found here.

Analyzing Inflation Rates

In this article I am going to demonstrate how to use shinydashboard and highcharter package in R to analyze and visualize Inflation rates of major economies and other economic and regional trade unions.

What are inflation rates

Inflation rates are the general rate at which price of the goods and services within a particular economy are rising and the purchasing power of the currency is declining due to the higher priced goods. High inflation is definitely not good for an economy because it will always reduce the value for money. In general central banks of an economy tries to and work towards reducing the inflation rate and avoiding deflation.

Deflation is opposite of inflation. Deflation occurs when the inflation rates become negative or are below 0. Deflation is more harmful and dangerous for an economy because it means that the prices of goods and services are going to decrease. Now, this sounds amazing for consumers like us. But what actually happens is that the demand for goods and services have declined over a long term of time. This directly indicates that a recession is on its way. This brings job losses, declining wages and a big hit to the stock portfolio. Deflation slows economy’s growth. As prices fall, people defer(postpone) purchases in hope of a better lower price deal. Due to this companies and firms have to cut down the cost of their goods and products which directly affects the wages of the employees which have to be lowered.

Now I won’t be explaining much about these economic terms. I leave these things for the readers to go check and read these things out. I am sure you will find such subjects quite interesting.

Lets start with designing UI in R

In shiny you have the choice to write UI and server-side code in a single file. But I prefer to write the client-side and server-side code in separate files for easy understanding and modularity and stop the things to get messed up if the code gets too long.

#loading the packages
library(shinydashboard)
require(shiny)
require(highcharter)
#layout of the dashboard
#defining character vectors for select inputs
country<-c("India","United States","Mexico","Canada","China, People's Republic of","Japan","Russian Federation","Germany","United Kingdom","European Union",
           "ASEAN-5","New Zealand","Australia","Netherlands","Luxembourg",
           "France","Qatar","United Arab Emirates","Saudi Arabia")

unions<-c("Major advanced economies (G7)","European Union","Emerging and Developing Europe","ASEAN-5","Commonwealth of Independent States",
          "Emerging and Developing Asia","Latin America and the Caribbean",
          "Middle East, North Africa, Afghanistan, and Pakistan")
#function used to define the dashboard 
dashboardPage(
  #defines header
  skin = "red",

#header of the dashboard
  dashboardHeader(
    title="Inflation Rates" ,
    dropdownMenu()
  ),
#defines sidebar of the dashboard
  dashboardSidebar(
    sidebarMenu(
     #the sidebar menu items
      menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")),
      menuItem("About", tabName = "about", icon = icon("th")),
      menuItem("Trade Unions",tabName="unions",icon=icon("signal")),
menuItem("World",tabName="world",icon=icon("globe"))      
)),
#defines the body of the dashboard
dashboardBody(
#to add external CSS
tags$head(
  tags$link(rel = "stylesheet", type = "text/css", href = "custom.css")
 ),
tabItems(
#First TAB Menu-dashboard- first argument should be the 'tabName' value of the menuItem function  
tabItem(tabName = "dashboard",
fluidRow(
       column(12,
#box() is similar to a 'div' element in HTML
  box(
     selectInput("country",label="Select Country",choices=country), width = 12)# end box 
),#end column
#box for plotting the time series plot
 column(12,
     box(
#below function is used to define a highcharter output plot which will be made in the server side
highchartOutput("hcontainer"),
          width="12") #end box2
          ), #end column
br(), #line break
h4("Relative inflation rates time series plot",align="center"),
   br(),
   column(12,
   box(highchartOutput("hc2"),width=12))
),#end row
h4("Made with love from", strong("Anish Singh Walia")),
  a("R code for this project",target="_blank",href="https://github.com/anishsingh20/Analzying-Inflation-Rates-Worldwide")
),
#second tab menu- ABOUT
tabItem(tabName="about",
 h2("What is Inflation ?",style="text-align:center"),
                    br(),
                    br(),
                    box(width=12,height="400px",
                        p(style="font-size:20px",strong("Inflation"),"rates are the general rate at which price of the goods and services within a particular economy are rising and the purchasing power of the currency is declining due to the higher priced goods. High inflation is definitely not good for an economy because it will always reduce the value for money.In general central banks of an economy tries to and work towards reducing the inflation rate and avoiding deflation."),
                          
p(style="font-size:20px",strong("Deflation"), "is opposite of inflation. Deflation occurs when the inflation rates become negative or are below 0. Deflation is more harmful and dangerous for an economy because it means that the prices of goods and services are going to decrease. Now, this sounds amazing for consumers like us. But what actually happens is that the demand for goods and services have declined over a long term of time. 
This directly indicates that a recession is on its way. This brings job losses, declining wages and a big hit to the stock portfolio. Deflation slows economy's growth. As prices fall, people defer(postpone) purchases in hope of a better lower price deal. Due to this companies and firms have to cut down the cost of their goods and products which directly affects the wages of the employees which have to be lowered.")
  )
    ),
tabItem(tabName = "unions", h3("Time series of Inflation rates of Economic trade unions",align="center") ,
 fluidRow(
       column(12,
       box(selectInput("region",label="Select Economic Region",choices=unions),width = 12) 
       ),
 box(highchartOutput("hc3"), width=12)
   )# end row 
   ),
tabItem(tabName = "world",
      h3("World's Inflation Rates",align="center") ,
   box(highchartOutput("hc4"), width=12)
   )
    )#end tabitems
 )#end body

)#end dashboard

Now, in the above code one can notice that the various functions which are used to design the UI are actually similar to the HTML elements. But in R shiny allows us to use those like functions and the HTML attributes as the function arguments. It’s hard to explain everything in the above code, but I insist the readers to check the documentation and help files of the above functions and go and check out the links to various resources which I will add at the end.

The highchartOutput(id) function which takes the ‘id’ as an argument which is used to define a high charter plot which will be developed and plotted at the server side. Here we only design and define the UI and layout of the dashboard.

Let’s write the Server logic

All the server-side code would be in a separate file named server.R. In the server side, it would only contain the logic to reactively and dynamically plot the various plots.

The inflation rates dataset is downloaded from IMF(International Monetary Fund) website and is publically available. I first had to do some preprocessing and transformations using the tidyr and dplyr packages to convert the dataset to the desired format.

require(shinydashboard)
require(ggplot2)
require(dplyr)
require(highcharter) #to plot amazing time series plots
library(readxl)
require(tidyr)
#loading the dataset
inflation <- read_excel("inflation.xls")
year<-c(1980:2022) #making a vector consisting of all years
year<-as.character(year)#converting to character type to use in gather()

#converting dataset to a long format
inf <- gather(year,key = "Year",value="InflationRate")
inf <- na.omit(inf) #omitting NA values
names(inf) <- c("region","year","inflation")
inf$year<- as.integer(inf$year)

#Making data frame for specific countries and economic unions to be used in plotting

India <- filter(inf,region=="India")
India$inflation<-as.numeric(India$inflation)
India$year<-as.numeric(India$year)
China<-filter(inf,region=="China, People's Republic of")
Ger<-filter(inf,region=="Germany")
Japan<-filter(inf,region=="Japan")
US<-filter(inf,region=="United States")
EU<-filter(inf,region=="European Union")
UK<-filter(inf,region=="United Kingdom")
Fr<-filter(inf,region=="France")
uae<-filter(inf,region=="United Arab Emirates")

#server function and logic
server <- function(input, output) { 
 output$hcontainer <- renderHighchart ({
  
             #write all R-code inside this

 df  <- inf %>% filter(region==input$country) #making the dataframe of the country
 #above input$country is used to extract the select input value from the UI and then make 
 #a dataframe based on the selected input
 df$inflation <- as.numeric(df$inflation)
 df$year <- as.numeric(df$year)

   #plotting the data
        hchart(df, "line",color="#DC270C",hcaes(x=year,y=inflation))  %>%
                  
           hc_exporting(enabled = TRUE) %>% 
           hc_tooltip(crosshairs = TRUE, backgroundColor = "#FCFFC5",
              shared = TRUE, borderWidth = 2) %>%
           hc_title(text="Time series plot of Inflation Rates",align="center") %>%
           hc_subtitle(text="Data Source: IMF",align="center") %>%
           hc_add_theme(hc_theme_elementary()) 

    }) # end hcontainer


output$hc2 <- renderHighchart({

 highchart() %>% 
        hc_xAxis(categories=inf$year) %>% 
        hc_add_series(name = "India", data = India$inflation) %>% 
        hc_add_series(name = "USA", data = US$inflation) %>%
        hc_add_series(name = "UK", data = UK$inflation) %>%
        hc_add_series(name = "China", data = China$inflation) %>%
        hc_add_series(name = "Germany", data = Ger$inflation) %>%
        hc_add_series(name="Japan",data=Japan$inflation) %>%
        #to add colors
        hc_colors(c("red","blue","green","purple","darkpink","orange")) %>%
        hc_add_theme(hc_theme_elementary())
}) # end hc2
    
output$hc3<-renderHighchart({
      union <- inf %>% filter(region==input$region)
      union$year <- as.numeric(union$year)
      union$inflation <- as.numeric(union$inflation)

    hchart(union,hcaes(x=year,y=inflation),type="area",color="#2B1F97") %>%
        hc_exporting(enabled = TRUE) %>% 
        hc_tooltip(crosshairs = TRUE, backgroundColor = "#FCFFC5",
                   shared = TRUE, borderWidth = 2) %>%
        hc_title(text="Time series plot of Inflation Rates for Economic Unions",align="center") %>%
        hc_subtitle(text="Data Source: IMF",align="center") %>%
        hc_add_theme(hc_theme_elementary())
}) #end hc3

    output$hc4<-renderHighchart({

      world <- inf %>% filter(region=="World")
      world$year<-as.numeric(world$year)
      world$inflation <-as.numeric(world$inflation)

     hchart(world,hcaes(x=year,y=inflation),type="area",color="#B915A3") %>%
        hc_exporting(enabled = TRUE) %>% 
        hc_tooltip(crosshairs = TRUE, backgroundColor = "#FCFFC5",
                   shared = TRUE, borderWidth = 2) %>%
        hc_title(text="Time series plot of Inflation Rates for World",align="center") %>%
        hc_subtitle(text="Data Source: IMF",align="center") %>%
         hc_add_theme(hc_theme_elementary())
      
    }) #end hc4
 }

In the above code we access the plot defined in the UI using their id in the form output$id. We use the function renderHighchart({ #write all R code and logic }) to render the plots and write all the R-code to develop any output inside it.v Inside this function as you all can notice is simply the R code to make plots.

Now the function hchart(df,type,hcaes(x,y)...) works in the same fashion as qplot. It takes data, type of plot, plot asthetics as its arguments. Rest things such as title, subtitle etc are piped to it like we piped extra things and plotting characteristics in ggplot. For more details read this http://jkunst.com/highcharter/hchart.html

Screenshots of the Dashboard:

Now deploying a shiny app is just a matter of minutes. You just need to have an account on shinyapps.io and it offers infrastructure as a service(IaaS) to run and manage you application. You can deploy you app directly from your Rstudio IDE.

Conclusion

This was just a short tutorial on how to make a dashboard in R and use shinydashboard and highcharter package in R. This article is not aimed to explain everything in detail,rather just demonstrate the use of shinydashboard and highcharter in R to build awesome dashboards and web apps.I will attach various resources below to help out with learning to develop web apps in R and which helped me out too.

Resources

Hope this article is motivating enough to at least get you started with learning and developing your own web apps in R and start using highcharter in R to visualize data. For any doubt or queries feel free to drop a comment. I will be happy to help. Do like and share the article.
Happy coding!