13.8 Layouts

There are several options for creating the layout of the user interface of a Shiny app. Here, we explain the layout called sidebar. The specification of other layouts can be seen in the RStudio website.

  • A user interface with a sidebar layout has a title, a sidebar panel for inputs on the left, and a main panel for outputs on the right.

  • To create this layout, we need to add a title for the app with titlePanel(), and use a sidebarLayout() to produce a sidebar with input and output definitions.

  • SidebarLayout() takes the arguments sidebarPanel() and mainPanel(). sidebarPanel() creates a a sidebar panel for inputs on the left, and mainPanel() creates a main panel for displaying outputs on the right.

All these elements are placed within fluidPage() so the app automatically adjusts to the dimensions of the browser window as follows:

ui <- fluidPage(
  titlePanel("title panel"),
  sidebarLayout(
    sidebarPanel("sidebar panel"),
    mainPanel("main panel")
  )
)
# load the shiny package
library(shiny)

# define the user interface object with the appearance of the app
ui <- fluidPage(
  titlePanel("Example of sidebar layout"),

  sidebarLayout(
    sidebarPanel(
      numericInput(
        inputId = "n", label = "Sample size",
        value = 25
      )
    ),

    mainPanel(
      plotOutput(outputId = "hist")
    )
  )
)

# define the server function with instructions to build the
# objects displayed in the ui
server <- function(input, output) {
  output$hist <- renderPlot({
    hist(rnorm(input$n))
  })
}

# call shinyApp() which returns the Shiny app object
shinyApp(ui = ui, server = server)