1 Introduction

Visualization is the straightest way to tell audience about how the figures look like. Most of time, presenters show static plots rather than dynamic plots. Giving user interactive plots can dramatically improve user experience and enhance visualisation flexibility as well.

The goal of this vignette is to introduce Shinny, a powerful R package which makes users interact with plots and analysis.

The Shinny R can work with R Markdown document, but it must be an HTML output format. So, this vignette assumed reader have a basic knowledge of R and R Markdown.

2 Preparation

  # Load libraries
  library(tidyverse)
  library(shiny)
  library(skimr)

To allow R Markdown HTML format output embedded with Shinny R, users need to add the line runtime: shiny to the YAML header.

3 Basics

There are 3 fundamentals within one Shinny app, which are user interface object, server function and a call to the shinyApp function. The most first two components make up the front end and back end of the shiyApp respectively. And the call of shinyApp(ui,server) is the integration of the two parts.

3.1 User Interface - UI

The UI objects have the information of layout and appearance of the shinyApp. There are plenty of different UI layouts listed in this page. The page functions like fluidPage(), fillPage() will create a page with corresponding page style. The panel functions like headerPanel(), siderbarPanel() will be used as different components within a page. In different panels, we can used it for inputs and outputs as interaction display.

Example:

ui <- fluidPage(
  titlePanel("Fill the App title here"),
  
  #Siderbar panel for inputs
  sidebarPanel(),
  
  #Main panel for displaying outputs
  mainPanel()
  
)

3.2 Server

The server object has all the information of the relationship between inputs and outputs. Inside the input, users can apply reactive() function to automatically re-execute when inputs change. For the output, user can make use of rendering functions such as readerPlot(), renderText() to generate output instead of assigning values directly. You can find more rendering function in this page.

3.3 Running an App

To embedded inline Shiny R applications, user can use an inline definition as below.

shinyApp(
  ui <- fluidPage(
    #content of ui
  ),
  server <- function(input,output){
    #content of server
  }
)

4 Examples

4.1 Example 1

For this example, it uses three datasets and gives a summary and view, respectively. The build-in datasets are mpg, diamonds and titanic. Understanding the dataset is a very important step of explore data analysis.

From the below code, we can find that there are 3 inputs inside the sidebarPanel() and 3 outputs inside mainPanel(). Please be aware of inputId, this will be referred in Server part. In the Server part, it describes the relationship between inputs and outputs. Also, renderText(), renderPrint can be re-executed once there is change in the Inputs()

shinyApp(
# Define UI for dataset viewer app ----
  ui <- fluidPage(
  # App title ----
  titlePanel("Summary of Dataset"),
  
  sidebarLayout(
    
    sidebarPanel (
      textInput(inputId = "caption",
                label = "Caption:",
                value = "Data Summary"),
      selectInput(inputId = "dataset",
                  label = "Choose a dataset",
                  choices = c("mpg", "diamonds","Titanic")),
      numericInput(inputId = "obs",
                   label = "Number of observations to view:",
                   value = 5)
    ),
    
    mainPanel(
      h3(textOutput("caption", container = span)),
      
      verbatimTextOutput("summary"),
      
      tableOutput("view")
    )
  )
  ),

server <- function(input, output) {
    
    datasetInput <- reactive({
      switch (input$dataset,
        "mpg" = mpg,
        "diamonds" = diamonds,
        "Titanic" = Titanic
      )
    })
  
    output$caption <- renderText({
    input$caption
    })
    
    output$summary <- renderPrint({
      dataset <- datasetInput()
      summary(dataset)
    })
    output$view <- renderTable({
      head(datasetInput(), n = input$obs)
  })

},

options = list(height = 800)
)
Shiny applications not supported in static R Markdown documents

4.2 Example 2

In this example, we add a slide bar input and a colour input within the sidebarPanel. The default value is specified by the argument value=. User can slide the bar to specify how many bins for the histogram. Meanwhile, user can fill the colour in the box as well. You can try different colour like “red”, “blue”, “#9970AB” “#C2A5CF” “#E7D4E8”

shinyApp(

ui <- fluidPage(
  titlePanel("Histogram"),
  sidebarLayout(
    sidebarPanel(
      sliderInput(inputId = "bins",
                  label = "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30),
      textInput(inputId = "color",
                label = "Color:",
                value = "blue"),
    ),
    mainPanel(
      plotOutput(outputId = "distPlot")
    )
  )
),
server <- function(input, output) {
  output$distPlot <- renderPlot({

    x    <- diamonds$price
    bins <- seq(min(x), max(x), length.out = input$bins + 1)

    hist(x, breaks = bins, col = input$color, border = "white",
         xlab = "Price of Diamonds",
         main = "Histogram of Diamond Price")
    })
}
)
Shiny applications not supported in static R Markdown documents

4.3 Example 3

In this example, we add an interaction by adding click plot which will show the x-axis and y-axis value when user click on the plot.

ui <- basicPage(
  plotOutput("plot1", click = "plot_click"),
  verbatimTextOutput("info")
)

server <- function(input, output) {
  output$plot1 <- renderPlot({
    ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy,color=class),size=4)
  })
  output$info <- renderText({
    paste0("x=", input$plot_click$x, "\ny=", input$plot_click$y)
  })
}

shinyApp(ui, server,options = list(height = 600))
Shiny applications not supported in static R Markdown documents

5 Extra Resources

Shiny R Articles: https://shiny.rstudio.com/articles/

Shiny R Tutorial: https://shiny.rstudio.com/tutorial/

Shiny R Document: https://shiny.rstudio.com/reference/shiny/1.5.0/

6 References

Grolemund, Y. X., J. J. Allaire, Garrett. (n.d.). 19.3 Embedded Shiny apps | R Markdown: The Definitive Guide. Retrieved August 16, 2020, from https://bookdown.org/yihui/rmarkdown/

RStudio. (2017, June 28). Shiny—The basic parts of a Shiny app. Shiny from Rstudio. https://shiny.rstudio.com/articles/basics.html