# Load libraries
library(shiny)
library(DT)
library(ggplot2)
# User Interface
ui <- fluidPage(
# Dropdown menu to select which column will be used for the x-axis
selectInput(inputId = "x_axis_input",
label = "Select x-axis",
choices = colnames(mtcars),
selected = "mpg"),
# Dropdown menu to select which column will be used for the y-axis
selectInput(inputId = "y_axis_input",
label = "Select y-axis",
choices = colnames(mtcars),
selected = "disp"),
# The output plot
plotOutput(outputId = "plot",
brush = "plot_brush"),
# The output table
DTOutput(outputId = "table")
)
# Server
server <- function(input, output) {
# Render the scatter plot
output$plot <- renderPlot({
# Scatter plot creation
ggplot(mtcars) +
geom_point(aes(x = .data[[input$x_axis_input]],
y = .data[[input$y_axis_input]]))
})
# Render a table from points within the rectangle created by clicking and dragging over the plot
output$table <- renderDT({
brushedPoints(df = mtcars,
brush = input$plot_brush,
xvar = input$x_axis_input,
yvar = input$y_axis_input)
})
}
# Run the app
shinyApp(ui = ui, server = server)Layout Practical - Answer Key
Exercise 1
Let’s enhance the layout of the app that we created in the practical exercise last session:
Let’s place the selectInput() in a sidebarPanel() and then in the mainPanel(), let’s use a tabset where the plot is in one tab and the brushed table is in another tab. The app should look like this:
# Load libraries
library(shiny)
library(DT)
library(ggplot2)
# User Interface
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
# Dropdown menu to select which column will be used for the x-axis
selectInput(inputId = "x_axis_input",
label = "Select x-axis",
choices = colnames(mtcars),
selected = "mpg"),
# Dropdown menu to select which column will be used for the y-axis
selectInput(inputId = "y_axis_input",
label = "Select y-axis",
choices = colnames(mtcars),
selected = "disp")
),
mainPanel(
tabsetPanel(
tabPanel(title = "Plot",
# The output plot
plotOutput(outputId = "plot",
brush = "plot_brush")
),
tabPanel(title = "Table",
# The output table
DTOutput(outputId = "table")
)
)
)
)
)
# Server
server <- function(input, output) {
# Render the scatter plot
output$plot <- renderPlot({
# Scatter plot creation
ggplot(mtcars) +
geom_point(aes(x = .data[[input$x_axis_input]],
y = .data[[input$y_axis_input]]))
})
# Render a table from points within the rectangle created by clicking and dragging over the plot
output$table <- renderDT({
brushedPoints(df = mtcars,
brush = input$plot_brush,
xvar = input$x_axis_input,
yvar = input$y_axis_input)
})
}
# Run the app
shinyApp(ui = ui, server = server)Reuse
CC-BY-4.0