Plot the data
Recall that plots are output objects, and as such they are added to a Shiny app using the plotOutput()
+ renderPlot()
functions. The output function is added to the UI to determine where to place the plot, and the render function in the server code is responsible for generating the plot.
Your task is to add a plot of GDP per capita vs life expectancy to the app. The data used in the plot should be the same data that is shown in the table; that is, the data in the plot should only show records that match the input filters. The code inside renderPlot()
does not have access to any variables defined inside renderTable()
, so you will have to literally copy and re-use the same code. Later on we'll learn how to avoid this duplication.
This exercise is part of the course
Case Studies: Building Web Applications with Shiny in R
Exercise instructions
- Add a placeholder for a plot output to the UI with an ID of "plot".
- In the server, use the appropriate render function to create the plot (line 30).
- Re-use the same data-filtering code that the output table uses for the plot data (line 32).
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
ui <- fluidPage(
h1("Gapminder"),
sliderInput(inputId = "life", label = "Life expectancy",
min = 0, max = 120,
value = c(30, 50)),
selectInput("continent", "Continent",
choices = c("All", levels(gapminder$continent))),
# Add a plot output
___(___),
tableOutput("table")
)
server <- function(input, output) {
output$table <- renderTable({
data <- gapminder
data <- subset(
data,
lifeExp >= input$life[1] & lifeExp <= input$life[2]
)
if (input$continent != "All") {
data <- subset(
data,
continent == input$continent
)
}
data
})
# Create the plot render function
output$plot <- ___({
# Use the same filtered data code that the table uses
data <- ___
___
___
ggplot(data, aes(gdpPercap, lifeExp)) +
geom_point() +
scale_x_log10()
})
}
shinyApp(ui, server)