# Define UI for application that draws a scatter plot
ui <- fluidPage(
# Application title
titlePanel("Democracy and Development"),
# Sidebar with a two dropdown menus
sidebarLayout(
sidebarPanel(
selectInput(input = 'xcol', label = 'X Variable', choices = vars),
selectInput(input = 'ycol', label = 'Y Variable',
choices = vars, selected = vars[[6]])
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("scatterplot")
)
)
)
Module 1.4
Scatter Plot App UI
- Read Mastering Shiny, Chapter 2
Overview
In this module we are going to continue our work on the scatter plot app by coding the basic elements of the user interface (UI). The user interface (UI) defines the layout and appearance of the web application. Here you tell Shiny what elements such as buttons, sliders, text inputs, plots, and other interactive components that you want users to be able to interact with.
Coding the UI
We will start with the fluidPage()
function as the outermost layer of our UI and then add additional container functions within it. First we will add a titlePanel()
. You are free to call this app whatever you like but I thought a good title would be “Democracy and Development.”
Then we can add a sidebar panel with dropdown menus to select the variables to display in the scatter plot. For this we call sidebarLayout()
and then within that sidebarPanel()
. This next step is really important. We are going to use the list variables called vars
from our setup code chunk to populate the dropdown menus. To do this we are going to call selectInput()
twice–once for the x-axis variable that the user wants to appear on the scatter plot and once for the y-axis variable.
The three main arguments for this function are input
, label
and choices
. input
is the input ID that we will use to access the user selection later on in the server function. label
refers to the name that we want to appear above the dropdown menu. And choices
refers to the list of choices to appear in the dropdown (in our case the list of variables called vars
.)
We can also include the argument selected
in our selectInput()
call to determine which variable is selected by default when the app loads. We are going to specify the sixth variable in the list for the y-axis (vars[[6]]
) to make sure that the same two variables do not appear on both the x and y axes.
The final piece of our UI is the main panel where we want our scatter plot to appear. Let’s go ahead and add mainPanel()
and then within that call plotOutput("scatterplot")
. This is going to dynamically retrieve the updated scatter plot as the user changes the variables in the dropdown menu.