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
Familiarize yourself and use the code in Section 2.4.
Change the website title to “A big name in politics”
Change the sidebar menu title with “The Arni Shiny App”.
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.
Solution: Using image from link
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)
Solution: Using image from www folder
Check the directory you are in with getwd().
Make sure the app.R file you are using is saved in this directory.
Use dir.create("www") or the buttons in Rstudio to create the www folder.
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
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)
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 categoriesui <-fluidPage(# Free texttextInput("name", "What's your name?"),passwordInput("password", "What's your password?"),textAreaInput("story", "Tell me about yourself", rows =3),# Numeric inputsnumericInput("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),# DatesdateInput("dob", "When were you born?"),dateRangeInput("holiday", "When do you want to go on vacation next?"),# Limited choicesselectInput("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 checkboxcheckboxInput("cleanup", "Clean up?", value =TRUE),checkboxInput("shutdown", "Shutdown?"),# File uploadsfileInput("upload", NULL),# Action buttonsactionButton("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!
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)
Solution
textInput("text", "", placeholder ="Your name")
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)
Solution
sliderInput("dates","When should we deliver?",min =as.Date("2019-08-09"),max =as.Date("2019-08-16"),value =as.Date("2019-08-10"))
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.
Solution
sliderInput("number", "Select a number:",min =0, max =100, value =0, step =5, animate =TRUE)
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>.)
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
In addition to Shiny UI base functions (that are accessible throught the shiny package), various other packages allow for more advanced UIs
dashboardPage() from the bs4Dash can be used to create dashboards (see Section 7.1)
Custom theming and modern UI widgets: bslib and bsplus