Skip to main content

Interactive Visualisation Using R



Shiny is an R package that makes it easy to build interactive web apps straight from R. You can host standalone apps on a webpage or embed them in R Markdown documents or build dashboards. (R Studio)

This one below is an example of how useful Shiny for data visualisation:
*Sudden changes starting in year 2010 caused by the implementation of new HDI method
Codes for the above visualisation:
library(shiny)
library(googleCharts)
library(dplyr)
library(readxl)
head(data)
## # A tibble: 6 x 6
##   woe_label     Island    year Grdpc   HDI Population
##   <fct>         <fct>    <dbl> <dbl> <dbl>      <dbl>
## 1 Aceh          Sumatera  2000 4995.  65.3    3930905
## 2 North Sumatra Sumatera  2000 5848.  66.6   11649655
## 3 West Sumatra  Sumatera  2000 5388.  65.8    4248931
## 4 Riau          Sumatera  2000 5746.  67.3    4957627
## 5 Jambi         Sumatera  2000 3503.  65.4    2413846
## 6 South Sumatra Sumatera  2000 4506.  63.9    6899675
xlim <- list(
  min = 1000,
  max = 160000
)
ylim <- list(
  min = 50,
  max = 85
)

ui <- fluidPage(
    googleChartsInit(),
  # Use the Google webfont "Source Sans Pro"
  tags$link(
    href=paste0("http://fonts.googleapis.com/css?",
                "family=Source+Sans+Pro:300,600,300italic"),
    rel="stylesheet", type="text/css"),
  tags$style(type="text/css",
             "body {font-family: 'Source Sans Pro'}"
  ),
  googleBubbleChart("chart",
                    width="100%", height = "420px",
                    # Set the default options for this chart; they can be
                    # overridden in server.R on a per-update basis. 
                    options = list(
                      fontName = "Source Sans Pro",
                      fontSize = 15,
                      # Set axis labels and ranges
                      hAxis = list(
                        scaleType = "log",
                        title = "GRDP per Capita per Year (RP 000)",
                        viewWindow = xlim
                      ),
                      vAxis = list(
                        title = "Human Development Index (HDI)",
                        viewWindow = ylim
                      ),
                      # The default padding is a little too spaced out
                      chartArea = list(
                        top = 50, left = 75,
                        height = "75%", width = "85%"
                      ),
                      # Allow pan/zoom
                      explorer = list(),
                      # Set bubble visual props
                      bubble = list(
                        opacity = 0.4, stroke = "none",
                        # Hide bubble label
                        textStyle = list(
                          color = "none"
                        )
                      ),
                      # Set fonts
                      titleTextStyle = list(
                        fontSize = 20
                      ),
                      tooltip = list(
                        textStyle = list(
                          fontSize = 12
                        )
                      )
                    )
  ),
  
  fluidRow(
    shiny::column(2, offset = 1, 
                  selectInput("Island", "Island", 
                              c("All",unique(as.character(data$Island))))),
    shiny::column(3, offset = 0.5,
                  sliderInput("year", "Year",
                  min = 2004, max = max(data$year),
                  value = 1, animate = TRUE)),
    shiny::column(5, offset = 0.5, 
                  h2("A region scores higher HDI when the lifespan is higher, the education level is higher, and the GRDP per capita is higher. However, having high GRDP per capita will not guarantee a region can score high HDI."))
    
  )
)

server <- function(input, output, session) {
  
  defaultColors <- c("#3366cc", "#dc3912", "#ff9900", "#109618", "#990099", "#0099c6")
  series <- structure(
    lapply(defaultColors, function(color) { list(color=color) }),
    names = levels(data$Island)
  )
  
  yearData <- reactive({
    # Filter to the desired year, and put the columns
    # in the order that Google's Bubble Chart expects
    # them (name, x, y, color, size). Also sort by Island
    # so that Google Charts orders and colors the Island
    # consistently.
    
    if (input$Island != "All") {
      df <- data %>%
        filter(year == input$year, Island== input$Island) %>%
        select(woe_label, Grdpc, HDI,
               Island, Population) %>%
        arrange(Island)
    }
    
    else 
      df <- data %>%
        filter(year == input$year) %>%
        select(woe_label, Grdpc, HDI,
               Island, Population) %>%
        arrange(Island)
    
    })
  
  output$chart <- reactive({
    # Return the data and options
    list(
      data = googleDataTable(yearData()),
      options = list(
        title = sprintf(
          "GRDP per Capita versus HDI in Indonesia, %s",
          input$year),
        series = series
      )
    )
  })
}


shinyApp(ui, server)

Comments

Popular posts from this blog

How to Create Indonesia Map in R

Creating the Map In this article, I will try to explain how to make Indonesia Map in R. I will assume that you are already familiar with the basic codes in R. First, we need the required libraries : require (maps) #loading maps package require (mapdata) #loading mapdata package library(ggplot2) #ggplot2 package library(readxl) #package for read .xlsx file library(ggthemes) #package for ggplot2 theme library(ggrepel) #extendig the plotting package ggplot2 for maps Then, we prepare the data that contains the information of provinces name, latitude, and longitude of every province in Indonesia, e.g. : You can download the data in here:  Data Now open the file and create the polygon: setwd( "your file's path" ) #set your own directory mydata<- read _xlsx( "dummy.xlsx" ) #assign the data to "mydata" View(mydata) #view the data, notice the column of "latitude","longitude", "woe_label" glo

Empirical Evidence of Engel’s Law Among Social Grant Recievers

Engel's law is an observation in economics stating that as income increases, the proportion of income spent on food decreases, even if absolute expenditure on food increases. The law was named after the statistician  Ernst Engel (1821–1896). One application of this statistic is treating it as a reflection of the living standard of a country. As this proportion — or "Engel coefficient" — increases, the country is by nature poorer; conversely a low Engel coefficient indicates a higher standard of living. Engel's Law image source: Wikipedia Using data collected through National Social and Economic Survey (NSES) by BPS-Statistics Indonesia, I tried to examine the existence of Engel's Law among households that received social grants in West Papua-Indonesia. Some studies found that giving additional money to the low-income households resulted in an increase in overall expenditure on food (on absolute) but the proportion  of income spent on food would decrea

What Can We Learn from Greek Debt Dramas?

Greek Debt Dramas Before the Global Financial Crisis (GFC) in 2008, the Greek had positive economic growth and it was considered high among countries in eurozone. Average economic growth reached almost four per cent between 1999 and 2007. Then the crisis hit in 2007 where housing bubble burst and made the subprime mortgage market in the United State collapsed. The crisis in the U.S. created a chain reaction which causing global banking crisis and credit crunch that lasts through 2009. The crisis made Lehman Brothers, big financial company, collapsed and the government in the United States and Europe prepared to bail out their banks. Greece failed to pay their huge debt since borrowing costs rose and financing dried up.  The financial crisis affected the Greek economy by reducing financial liquidity and business activity. Greece had been fortunate enough to face the crisis with the euro instead of its national currency, if they were using their national currency the crisis would