5/3/2018

Goal

Due to the lack of my imagination, I decided to showcase the exercise with a interactive histogram of the dataset Iris, that is built in R. The renderPlot() and plotOutput() funciton are utilized to display the plot. There are input widget that I included in the project to showcase what I learned: selectInput(), sliderInput() and radioButton().

Slide with Code

First we explore the data

## 'data.frame':    150 obs. of  5 variables:
##  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
##  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
##  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
##  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
##  $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

UI.R

#
# This is the user-interface definition of a Shiny web application. You can
# run the application by clicking 'Run App' above.
#
# Find out more about building applications with Shiny here:
# 
#    http://shiny.rstudio.com/
#

library(shiny)

# Define UI for application that draws a histogram
shinyUI(fluidPage(
  
  # Application title
  titlePanel("IRIS dataset render plot"),
  
  # Sidebar with a slider input for number of bins 
  sidebarLayout(
    sidebarPanel(
      selectInput("variable","1.Select Variable from the dataset",
                  choices = c("Sepal.Length"=1,"Sepal.Width"=2, 
                              "Petal.Length"=3, "Petal.Width"=4), selected = 1),
       sliderInput("bins",
                   "Number of bins for Histogram:",
                   min = 1,
                   max = 20,
                   value = 5),
      radioButtons("color", "3.Select the color of Graph",
                   choices = c('blue','red','green'),
                   selected = 'blue')
    ),
    
    # Show a plot of the generated distribution
    mainPanel(
       plotOutput("distPlot")
    )
  )
))

Server R

#code
library(shiny )

# Define server logic required to draw a histogram
shinyServer(function(input, output) {
   
  output$distPlot <- renderPlot({
    
    # generate bins based on input$bins from ui.R
    x    <-  as.numeric(input$variable)
    bins <- seq(0, max(iris[,x]), length.out = input$bins + 1)
    
    # draw the histogram with the specified number of bins
    hist(iris[,x], breaks = bins, col = input$color, border = 'white',
         xlab = names(iris[x]), main = "Histogram of Iris")
    
  })
  
})