User Interface (UI): Designing the front end

Source(s): Wickham (2021, Ch. 2)

1 Basics

  • Shiny encourages separation of code that generates UI (front end) from code that drives app’s behaviour (server/back end).
  • Here focus on front end & tour of Shiny inputs and outputs
    • won’t stitch inputs and outputs together yet
  • primary focus on native Shiny components (contained in Shiny package) but vibrant community (see awesome shiny extenstions)

2 UI: Layout

  • Any Shiny app consists of ui, server and shinyApp(ui=ui, server = server)
    • ui <- function(): function is used to create UI
      • UI then displays different inputs and outputs
    • Shiny provides different functions that can be used to create basic layouts
  • fluidPage() creates the classic fluid page layout

2.1 fluidPage (1)

  • fluidPage(): Creates most basic layout
    • display that automatically adjusts to user’s browser dimensions (smartphone!)
    • layout consists of rows containing columns
      • rows making sure elements appear on the same line
      • columns define usage of horizontal space (within a 12-unit wide grid)
  • UI with title panel and sidebar panel
    • titlePanel() and sidebarLayout() create a basic Shiny app/layout with a sidebar
    • sidebarLayout() takes two functions
      • sidebarPanel(): Includes content displayed in the sidebar
      • mainPanel(): Includes content displayed in the main panel
    • fluidRow() and column(): Divide ui into rows/columns
  • Try code below by pasting it into your console and running it
Code: Creating a simple UI
ui <- fluidPage(
  titlePanel("This is the title panel"),
  
  sidebarLayout(
    sidebarPanel( "Title: Sidebar panel"),
    
    mainPanel("Title: Main panel",
              fluidRow(
                column(width = 4,"Column 1: Description here"),
                column(width = 4, "Column 2: Model summary")
                ,
                column(width = 3, 
                       offset = 1, 
                       "Column 3: Model visualization")
              )
  )))

server <- function(input, output, session){}

shinyApp(ui=ui, server = server)

2.2 fluidPage (2)

  • Change sidebarLayout(position = "right",...) to position sidebar on the right
  • Sometimes adding borders helps to understand the UI
Code: Adding borders for better understanding of UI
ui <- fluidPage(
  titlePanel("This is the title panel"),
  
  sidebarLayout(
    sidebarPanel( "Title: Sidebar panel"),
    
    mainPanel("Title: Main panel",
              fluidRow(
                column(style='border: 1px solid black',
                       width = 4,"
                       Column 1: Description here"),
                column(style='border: 1px solid black',
                       width = 4, "Column 2: Model summary")
                ,
                column(style='border: 1px solid black',
                       width = 3, 
                       offset = 1, 
                       "Column 3: Model visualization")
              )
    )))

server <- function(input, output, session){}

shinyApp(ui=ui, server = server)

2.3 fluidPage (3): Creating panels and tabs

  • tabsetPanel() + tabPanel()
    • Allows for using sidebar layout but dividing main panel into tabs
    • Users can switch between tabs that show different outputs
ui <- fluidPage(
  titlePanel("This is the title panel"),
  
  sidebarLayout(
    sidebarPanel( "This is the sidebar panel"),
    
    mainPanel(
      tabsetPanel(type = "tabs",
                  tabPanel("3d Frequency Plot", 
                           "Tab 1: plot here"),
                  tabPanel("Histogram", 
                           "Tab 2: another plot here"),
                  tabPanel("Model Summary", 
                           h4("Tab 3: estimation results here")),
                  tabPanel("Data Summary", 
                           h4("Tab 4: Variable summaries"))
      ))))
  
  server <- function(input, output, session){}
  
  shinyApp(ui=ui, server = server)

2.4 Images

  • img() function places an image
    • img(src = "http://.../img-2.jpg", height = 35, width = 35): Load image from website or folder
  • Store image(s) locally
    • www subfolder stores all sorts of additional files(images, data etc.)
    • If working directory = app directory create with: dir.create("www")
    • Images place in folder www can be referenced without the www folder name/path
      • e.g., img(src = "guerry.jpg", width = "100%")
Code: Adding images
ui <- fluidPage(
  titlePanel(span(img(src = "https://www.gesis.org/typo3conf/ext/gesis_web_ext/Resources/Public/webpack/dist/img/logo_gesis_en.svg", style = "height: 1.4em;"), "The ESS shiny app")),
  
  sidebarLayout(
    sidebarPanel( "This is the sidebar panel"),
    
    mainPanel(
      tabsetPanel(type = "tabs",
                  tabPanel("An image", 
                           img(src = "https://journals.openedition.org/belgeo/docannexe/image/11893/img-1.jpg", width = 358, height = 476))
      ))))

server <- function(input, output, session){}

shinyApp(ui=ui, server = server)

2.5 Exercise: UI layout

  1. Familiarize yourself and use the code in Section 2.4.
  2. Change the website title to “A big name in politics”
  3. Change the sidebar menu title with “The Arni Shiny App”.
  4. Replace the image of Guerry with an image Arnold Schwarzenegger from the web, e.g., here.
  • Either store the image in a www subfolder of your app directory or use the URL in your code.
ui <- fluidPage(
  titlePanel(span(img(src = "https://www.gesis.org/typo3conf/ext/gesis_web_ext/Resources/Public/webpack/dist/img/logo_gesis_en.svg", style = "height: 1.4em;"), "A big name in politics")),
  
  sidebarLayout(
    sidebarPanel( "The Arni Shiny App"),
    
    mainPanel(
      tabsetPanel(type = "tabs",
                  tabPanel("An image", 
                           img(src = "http://assets.schwarzenegger.com/images/img-2.jpg", 
                  width = 729, height = 423))
      ))))

server <- function(input, output, session){}

shinyApp(ui=ui, server = server)
  1. Check the directory you are in with getwd().
  2. Make sure the app.R file you are using is saved in this directory.
  3. Use dir.create("www") or the buttons in Rstudio to create the www folder.
  4. Store the image from the link in this www folder.
  5. Add the image name simply in the code img(src = "img-2.jpg", width = 729, height = 423) (see below).
  • IMAGES PLACED UNDER www CAN BE REFERENCED WITHOUT THE www FOLDER NAME
  1. Run the app.
ui <- fluidPage(
  titlePanel(span(img(src = "https://www.gesis.org/typo3conf/ext/gesis_web_ext/Resources/Public/webpack/dist/img/logo_gesis_en.svg", style = "height: 1.4em;"), "A big name in politics")),
  
  sidebarLayout(
    sidebarPanel( "The Arni Shiny App"),
    
    mainPanel(
      tabsetPanel(type = "tabs",
                  tabPanel("An image", 
                           img(src = "img-2.jpg", 
                  width = 729, height = 423))
      ))))

server <- function(input, output, session){}

shinyApp(ui=ui, server = server)

3 UI: Inputs

3.1 UI Inputs: common structure

  • textInput(inputId = "username", label = "Enter your username", value = "Write here")
    • inputId connects front end with back end, e.g., if UI has input with ID name, the server function will access it with input$name
      • name` = simple string (only letters, numbers, and underscores) and unique
    • label argument: Used to create human-readable label
    • value argument: usually let’s you set default value
  • Inputs are stored in list called input$...
  • Remaining 4+ arguments are unique to the particular input
  • Recommendation: Supply inputId and label arguments by position, and all other arguments by name
  • Q: How would we read the following?
    • sliderInput("min", "Limit (minimum)", value = 50, min = 0, max = 100)

3.2 UI Inputs: Logic

  • Widget = Web element the user can interact with (Shiny widget gallery)
    • Users can send messages to the SERVER/Computer (e.g. “I want to choose this variable”)
  • Underlying logic is the same for all widgets
    • User uses widget to give input
    • Input is inserted into the functions in the SERVER
      • server <- function(input, output, session) {}
  • shiny package contains many widgets
    • Additional ones in other packages (e.g., pickerInput() in shinyWidgets package)

3.3 UI Inputs: Exercise

  • Read the code below. Can you guess what kind of inputs the various input functions create?
library(shinyWidgets) # Install!

animals <- c("dog", "cat", "mouse") # Predefining some categories

ui <- fluidPage(
  
  # Free text
  textInput("name", "What's your name?"),
  passwordInput("password", "What's your password?"),
  textAreaInput("story", "Tell me about yourself", rows = 3),
  
  # Numeric inputs
  numericInput("num", "Number one", value = 0, min = 0, max = 100),
  sliderInput("num2", "Number two", value = 50, min = 0, max = 100),
  sliderInput("rng", "Range", value = c(10, 20), min = 0, max = 100),
  
  # Dates
  dateInput("dob", "When were you born?"),
  dateRangeInput("holiday", "When do you want to go on vacation next?"),
  
  # Limited choices
  selectInput("state", "What's your favourite animal?", animals),
  radioButtons("animal", "What's your favourite animal?", animals),
  selectInput( "state", "What's your favourite animal?", animals, multiple = TRUE),
  checkboxGroupInput("animal2", "What animals do you like?", animals),
  pickerInput(
    inputId = "animal3",
    label = "What animals do you like?",
    choices = animals
  ),
  
  # Single checkbox
  checkboxInput("cleanup", "Clean up?", value = TRUE),
  checkboxInput("shutdown", "Shutdown?"),
  
  # File uploads
  fileInput("upload", NULL),
  
  # Action buttons
  actionButton("click", "Click me!"),
  actionButton("drink", "Drink me!", icon = icon("cocktail"))
)

server <- function(input, output, session) {}

shinyApp(ui, server)
  • Now try to run the code within Rstudio and take a look at the app itself!

3.4 Additional exercise(s)

  1. When space is at a premium, it’s useful to label text boxes using a placeholder that appears inside the text entry area. How do you call textInput() to generate the UI in Figure 1 below (see ?textInput)?
Figure 1: Text input (Source: Wickham 2021)
textInput("text", "", placeholder = "Your name")
  1. Carefully read the documentation for sliderInput() to figure out how to create a date slider, as shown below in Figure 2.
Figure 2: Date slider (Source: Wickham 2021)
sliderInput(
  "dates",
  "When should we deliver?",
  min = as.Date("2019-08-09"),
  max = as.Date("2019-08-16"),
  value = as.Date("2019-08-10")
)
  1. Create a slider input to select values between 0 and 100 where the interval between each select able value on the slider is 5. Then, add animation to the input widget so when the user presses play the input widget scrolls through the range automatically.
  sliderInput("number", "Select a number:",
              min = 0, max = 100, value = 0, 
              step = 5, animate = TRUE)
  1. If you have a moderately long list in a selectInput(), it’s useful to create sub-headings that break the list up into pieces. Read the documentation to figure out how. (Hint: the underlying HTML is called <optgroup>.)
selectInput(
  "breed",
  "Select your favorite animal breed:",
  choices =
    list(`dogs` = list('German Shepherd', 'Bulldog', 
                       'Labrador Retriever'),
         `cats` = list('Persian cat', 'Bengal cat', 
                       'Siamese Cat'))
)
ui <- fluidPage(
  textInput("text", "", placeholder = "Your name"),
  
  sliderInput(
  "dates",
  "When should we deliver?",
  min = as.Date("2019-08-09"),
  max = as.Date("2019-08-16"),
  value = as.Date("2019-08-10")
  ),
 
    sliderInput("number", "Select a number:",
              min = 0, max = 100, value = 0, 
              step = 5, animate = TRUE),
  
  selectInput(
  "breed",
  "Select your favorite animal breed:",
  choices =
    list(`dogs` = list('German Shepherd', 'Bulldog', 
                       'Labrador Retriever'),
         `cats` = list('Persian cat', 'Bengal cat', 
                       'Siamese Cat'))
)
  
)
server <- function(input, output, session) {
  
  
}
shinyApp(ui, server)
#rm(list=ls())
library(shiny)

ui <- basicPage(
  textInput("text", "", placeholder = "Your name"),
  
  sliderInput(
    "dates",
    "When should we deliver?",
    min = as.Date("2019-08-09"),
    max = as.Date("2019-08-16"),
    value = as.Date("2019-08-10")
  ),
  
  sliderInput("number", "Select a number:",
              min = 0, max = 100, value = 0, 
              step = 5, animate = TRUE),
  
  selectInput(
    "breed",
    "Select your favorite animal breed:",
    choices =
      list(`dogs` = list('German Shepherd', 'Bulldog', 
                         'Labrador Retriever'),
           `cats` = list('Persian cat', 'Bengal cat', 
                         'Siamese Cat'))),
  tableOutput('show_inputs')
)
server <- shinyServer(function(input, output, session){
  
  AllInputs <- reactive({
    myvalues <- NULL
    for(i in 1:length(names(input))){
      myvalues <- as.data.frame(rbind(myvalues,(cbind(names(input)[i],input[[names(input)[i]]]))))
    }
    names(myvalues) <- c("User Input","Last Value")
    myvalues
  })
  
  output$show_inputs <- renderTable({
    AllInputs()
  })
})
shinyApp(ui = ui, server = server)

4 UI: Outputs

  • Outputs in UI create placeholders that are later filled by the server function
  • Have unique ID as first argument like inputs
    • e.g., textOutput("text") as ID text that is filled by the server
  • If UI specification creates an output with ID text, you’ll access it in the server function with output$text (see below)
  • Each output function on the front end is coupled with a render function in the back end (server)
  • Three main types of output: text, tables, and plots

4.1 Text output

  • Below an example for text output
ui <- fluidPage(
  textOutput("text"),
  verbatimTextOutput("code")
)
server <- function(input, output, session) {
  output$text <- renderText({ 
    "Hello friend!" 
  })
  output$code <- renderPrint({ 
    summary(1:10) 
  })
}
shinyApp(ui, server)

4.2 Table output

  • Below an example for table output
ui <- fluidPage(
  tableOutput("static"),
  dataTableOutput("dynamic")
)
server <- function(input, output, session) {
  output$static <- renderTable(head(mtcars))
  output$dynamic <- renderDataTable(mtcars, options = list(pageLength = 5))
}
shinyApp(ui, server)

4.3 Plot output

  • Below an example for plot output
ui <- fluidPage(
  plotOutput("plot", width = "400px")
)
server <- function(input, output, session) {
  output$plot <- renderPlot(plot(1:5), res = 96)
}
shinyApp(ui, server)

4.4 Exercise(s)

  1. Which of textOutput() and verbatimTextOutput() should each of the following render functions be paired with?
  1. renderPrint(summary(mtcars))
  2. renderText("Good morning!")
  3. renderPrint(t.test(1:5, 2:6))
  4. renderPrint(str(lm(mpg ~ wt, data = mtcars)))
ui <- fluidPage(
  verbatimTextOutput("mtcarsout1"),
  br(), hr(),
  textOutput("mtcarsout2"),
  br(), hr(),
  verbatimTextOutput("mtcarsout3"),
  br(), hr(),
  verbatimTextOutput("mtcarsout4")  
)
server <- function(input, output, session) {
  output$mtcarsout1 <- renderPrint(summary(mtcars))
  output$mtcarsout2 <- renderText("Good morning!")
  output$mtcarsout3 <- renderPrint(t.test(1:5, 2:6))
  output$mtcarsout4 <- renderPrint(str(lm(mpg ~ wt, data = mtcars)))
}
shinyApp(ui, server)
  1. Update the options in the call to renderDataTable() below so that the data is displayed, but all other controls are suppress (i.e. remove the search, ordering, and filtering commands). You’ll need to read ?renderDataTable and review the options at https://shiny.posit.co/r/gallery/widgets/datatables-options/ by checking the code (or https://datatables.net/reference/option/).
ui <- fluidPage(
      dataTableOutput("table")
    )
    server <- function(input, output, session) {
      output$table <- renderDataTable(mtcars, options = list(pageLength = 5))
    }
shinyApp(ui, server)
ui <- fluidPage(
  dataTableOutput("table")
)
server <- function(input, output, session) {
  output$table <- renderDataTable(mtcars, 
                                  options = list(pageLength = 5,
                                                 searching = FALSE,
                                                 paging = FALSE,
                                                 ordering = FALSE,
                                                 filtering = FALSE))
}
shinyApp(ui, server)

4.5 Overview of Output functions

  • Output functions
    • htmlOutput()… creates raw HTML
    • imageOutput()… creates image
    • plotOutput()… creates plot
    • plotlyOutput … creates plotly graph (!)
    • tableOutput()… creates table (!)
    • textOutput()… creates text
    • uiOutput()… creates raw HTML
    • verbatimTextOutput()… creates text
    • dataTableOutput()… creates a data table (interactiv)
    • leafletOutput() … creates leaflet map (!)
  • Our example app uses those marked with (!).

5 HTML tag functions

  • Shiny’s HTML tag functions translate input into html code
    • Try pasting h2("A NEW HOPE", align = "center") into your console
    • h2() function creates <h2></h2> html tag
  • Common HTML tags (e.g., ⁠<div>⁠) can be created by calling for their tag name directly (e.g., div())
  • Less common tags (e.g., ⁠<article>⁠), use the tags list collection (e.g., tags$article()) stored in the tags object
    • Try tags$ in the console
      • .noWS = ... argument to remove whitespace
  • See full reference for HTML tags
  • Here we just do a quick example but in this tutorial you find more information
  • Exercise: Please run the shiny app below and explore the effect of different html tags. What do the different html tags do?
ui <- fluidPage(
  titlePanel("A big name in politics"),

sidebarLayout(
  sidebarPanel( "The Arni Shiny App"),
  
  mainPanel(
    
    h2("A NEW HOPE", align = "center"),
    h5("It is a period of civil war.", align = "center"),
    p("p creates a paragraph of text."),
    tags$p("A new p() command starts a new paragraph. Supply a style attribute to change the format of the entire paragraph.", style = "font-family: 'times'; font-si16pt"),
    strong("strong() makes bold text."),
    em("em() creates italicized (i.e, emphasized) text."),
    tags$hr(style="border-color:black;"),
    tags$br(),
    tags$line(),
    br(),
    code("code displays your text similar to computer code"),
    div("div creates segments of text with a similar style. This division of text is all blue because I passed the argument 'style = color:blue' to div", style = "color:blue"),
    br(),
    p("span does the same thing as div, but it works with",
      span("groups of words", style = "color:blue"),
      "that appear inside a paragraph.")
    
  )))

server <- function(input, output, session){}

shinyApp(ui=ui, server = server)

6 Summary

  • UI Layout created with fluidPage()
  • Image can be included using img(src = "...", , width = ..., height = ...) function
  • *Input() functions: Used to generate input UI widgets
    • input values are stored in list input$... with particular name, e.g., input$tab_tabulate_select
  • *Output() functions: Used to display output, dataTableOutput()
    • output is sent from server
  • Both input/output functions have IDs the connect them to the server
  • HTML tags can be used through tags$name() function, e.g., tags$br()
  • Not covered here:
    • Dynamic UI makes it possible to change UI as a function of input values (cf. uiOutput())

7 Other important concepts, functions and packages

7.1 dashboardPage

  • Alternative to fluidPage()
  • dashboardPage(): creates a dashboard interface
    • function contained in packages shinydashboard and bs4Dash (use bs4Dash1!)
    • dashboardHeader(): creates a dashboard header
    • dashboardSidebar(): Creates dashboard sidebar
      • sidebar typically contains a sidebarMenu, although it may also contain a sidebarSearchForm, or other Shiny inputs.
    • dashboardBody(): creates main body typically containing boxes or tabItems
library(bs4Dash)
# UI ----
ui <- dashboardPage(title = "The ESS shiny app",
                    
                    ### Header ----
                    header = dashboardHeader("Add title here"),
                    
                    ### Sidebar ----
                    sidebar = dashboardSidebar("Sidebar menu"),
                    
                    ### Body ----
                    body = dashboardBody("Main body")
)

# Server ----
server <- function(input, output, session) {}

shinyApp(ui, server)



  • ?sidebarMenu(): create sidebarMenu within dashboardSidebar
    • menuItem(tabName = "...", text = "...", icon = icon("table")): Creates one item in sidebarMenu
  • tabItems(): creates container for tab items
    • tabItem(tabName = "insp", ...): creates tab to put inside a tab items container
    • can be combined with fluidRow() and column()
    • Connection through name tabName argument
library(bs4Dash)
# UI ----
ui <- dashboardPage(title = "The ESS shiny app",

  ### Header ----
  header = dashboardHeader(
    title = "Title here"
  ),

  ### Sidebar ----
  sidebar = dashboardSidebar(
    sidebarMenu(
      menuItem(tabName = "tab_table", 
               text = "Table data", 
               icon = icon("table"))
    )
  ),
  ### Body ----
  body = dashboardBody(
    tabItems( # start tabItems

      tabItem(
        tabName = "tab_table",
        hr(), # add separation line
        "Here we will put a table"
      )
      
    ) # end tabItems
  )
) # End UI


# Server ----
server <- function(input, output, session) {}

shinyApp(ui, server)

References

Wickham, Hadley. 2021. Mastering Shiny. " O’Reilly Media, Inc.".

Footnotes

  1. Bootstrap 4 shinydashboard using AdminLTE3: Website↩︎