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...

Who Retweets Whom? A Quantitative and Qualitative Analysis of a Social Network

Social network analysis (SNA) is the process of investigating social structures using networks and graph theory. It characterizes networked structures in terms of nodes or vertex (individual actors, people, or things within the network) and the ties, edges, or links (relationships or interactions) that connect them. I won’t talk too much detail on the SNA theories as you can easily find them on the internet. There are some sources that provide data for SNA such as Stanford  and kdnuggets . In this simple analysis, I extract Twitter retweet data using “twitteR” package and analyse network retweet of a certain topic using “igraph” package in R. This tutorial from cosmopolitanvan may help you to replicate this work. As one of the largest social networks on the Internet, Twitter can be used for expanding your business or website's audience. It is free to create an account, it is easy to start tweeting to promote your work or share your ideas and thoughts. Twitter has 284 mil...

Big Data in Credit Scoring

Global Findex (Financial Inclusion Index) report which was released in 2018 shows only 48.9 percent of the adults in Indonesia own a bank account. Millions of unbanked Indonesian adults work in private sector and get paid in cash. What is the main reason to these young adults not having bank account? the reason is the distance and surprisingly 69 percent of this population segment have their own mobile phone.  We see some efforts from the banking institution to reach out this unbanked population but it is not enough, there is still a wide gap.  We may now realize that why there are many advanced technology multi-finance companies occur in the recent years, these companies fill the gap. They know the characteristics of the unbanked population and by utilizing the technology they can reach out more of this population. But, reaching this population is not without some risks. Multi-finance companies compete with each other to capture the market, they will offer many ...