Add colours to your plot: radio buttons
Radio buttons are used when you want to present the user with several options and ask them to choose one. They have a choices
parameter that defines the different options the user can choose from, and a selected
argument that defines which choice is selected initially. Note that there is no value
parameter, though you can think of selected
as having a similar role.
This exercise is part of the course
Case Studies: Building Web Applications with Shiny in R
Exercise instructions
The code for the Shiny app from the last exercise is provided. Your task is to add radio buttons that give the user a choice of color to use for the plot. Specifically:
- Add radio buttons to the UI with ID "color", a label of "Point color", and four choices: "blue", "red", "green", "black".
- Add code to the server such that the points in the plot will have the color that is selected in the radio buttons (line 22).
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Define UI for the application
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
textInput("title", "Title", "GDP vs life exp"),
numericInput("size", "Point size", 1, 1),
checkboxInput("fit", "Add line of best fit", FALSE),
# Add radio buttons for colour
___("color", ___, ___)
),
mainPanel(
plotOutput("plot")
)
)
)
# Define the server logic
server <- function(input, output) {
output$plot <- renderPlot({
p <- ggplot(gapminder, aes(gdpPercap, lifeExp)) +
# Use the value of the color input as the point colour
geom_point(size = input$size, col = input$___) +
scale_x_log10() +
ggtitle(input$title)
if (input$fit) {
p <- p + geom_smooth(method = "lm")
}
p
})
}
# Run the application
shinyApp(ui = ui, server = server)