Adding structure to your app
Layouts in Shiny are used to give your app some structure by placing elements in certain desired positions.
A sidebar layout, created with the sidebarLayout()
function, provides a basic two-column structure with a smaller sidebar on the left and a larger main panel on the right.
The sidebar layout function takes two arguments: sidebarPanel()
and mainPanel()
. Each of these panels can contain any arbitrary mix of text/HTML elements, in a similar fashion to how you can mix these elements inside a fluidPage()
.
This exercise is part of the course
Case Studies: Building Web Applications with Shiny in R
Exercise instructions
Your task is to add a sidebar layout to the existing app, such that the inputs will be on the left side and the outputs will be in the main panel. Specifically, you need to:
- Define the UI for the Shiny application.
- Add a sidebar layout to the page.
- Add a sidebar panel to the layout, and place the inputs and text in it.
- Add a main panel to the layout, and place the plot and table in it.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Load the shiny package
library(shiny)
# Define UI for the application
ui <- ___(
# Add a sidebar layout to the application
___(
# Add a sidebar panel around the text and inputs
___(
h4("Plot parameters"),
textInput("title", "Plot title", "Car speed vs distance to stop"),
numericInput("num", "Number of cars to show", 30, 1, nrow(cars)),
sliderInput("size", "Point size", 1, 5, 2, 0.5)
),
# Add a main panel around the plot and table
___(
plotOutput("plot"),
tableOutput("table")
)
)
)
# Define the server logic
server <- function(input, output) {
output$plot <- renderPlot({
plot(cars[1:input$num, ], main = input$title, cex = input$size)
})
output$table <- renderTable({
cars[1:input$num, ]
})
}
# Run the application
shinyApp(ui = ui, server = server)