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

Modifying Some Plots in R

Grant Data : 500 Households that get Social Grant in a certain region, the data comes from Social and Economic Survey. Download the dummy data:  DATA grant <- read.csv( "grant.csv" ) #PFOODEXP: Proportion of Food Expenditure to Total Expenditure #HH_Income: Household Income ($) #HH_FOOD: Household Food Expenditure ($) #HH_Loc: Household Location (0: Rural, 1: Urban) #Educ_H: Household Head Education (Year) #HH_Size: Household Family Member #Gender_H: Household Head Gender (0: Female, 1: Male ) #Age_H: Household Head Age #Remove 1st column grant[ 1 ] <- NULL #change variable type to factor grant$Gender_H <- as.factor(grant$Gender_H) grant$HH_Loc <- as.factor(grant$HH_Loc) head(grant) ## PFOODEXP HH_Food HH_Loc Gender_H Age_H Educ_H HH_Size HH_Income ## 1 73.16933 675.1766 1 0 32 22 4 922.7590 ## 2 69.77417 596.2286 1 1 27 22 13 854.5119 ## 3 63.31992 585.4946 0 1 42 15...