Add a plot title: text input
In Shiny, as soon as the user changes the value of any input, Shiny makes the current value of that input immediately available to you in the server through the input
argument of the server function. You can retrieve the value of any input using input$<inputId>
.
In order to assign a default initial value to a text input, the value
argument is used.
This exercise is part of the course
Case Studies: Building Web Applications with Shiny in R
Exercise instructions
The given Shiny app plots the GDP per capita vs life expectancy of countries in the gapminder dataset. Your task is to add a text input that lets users change the title of the plot. Specifically:
- Add a text input to the UI with ID "title", a label of "Title", and a default value of "GDP vs life exp".
- In the server code, make the title of the plot always reflect the current value of the title input by placing the title inside the
ggtitle()
function (line 24).
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Load the ggplot2 package for plotting
library(ggplot2)
# Define UI for the application
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
# Add a title text input
___(___, ___, ___)
),
mainPanel(
plotOutput("plot")
)
)
)
# Define the server logic
server <- function(input, output) {
output$plot <- renderPlot({
ggplot(gapminder, aes(gdpPercap, lifeExp)) +
geom_point() +
scale_x_log10() +
# Use the input value as the plot's title
ggtitle(___)
})
}
# Run the application
shinyApp(ui = ui, server = server)