开始使用免费开始使用

App 3: Popular Baby Names Redux

Great! Hope you enjoyed building that app displaying popular baby names as a column plot. Let us wrap this chapter up by enhancing the app we built earlier by adding a table showing the top 10 baby names as a tab. Your final app should visually resemble the screenshot below.

An app where the name selector  and year slider appears in the left sidebar, while the graph and table appear as tabs on the right in the main panel

Note that we have provided a function get_top_names() to extract the top 10 names for a given year and sex. You can get the top 10 male names for the year 2000 using get_top_names(2000, "M").

本练习是课程的一部分

Building Web Applications with Shiny in R

查看课程

练习说明

  • The code provided is for the app you built in the previous exercise. Modify this code to add an output to the server to display a table of popular names.
  • Lay out the plot and table outputs in the UI as tabs.

交互式实操练习

通过完成这段示例代码来试试这个练习。

# MODIFY this app (built in the previous exercise)
ui <- fluidPage(
  titlePanel("Most Popular Names"),
  sidebarLayout(
    sidebarPanel(
      selectInput('sex', 'Select Sex', c("M", "F")),
      sliderInput('year', 'Select Year', min = 1880, max = 2017, value = 1900)
    ),
    mainPanel(
     plotOutput('plot')
    )
  )
)

server <- function(input, output, session) {
  output$plot <- renderPlot({
    top_names_by_sex_year <- get_top_names(input$year, input$sex) 
    ggplot(top_names_by_sex_year, aes(x = name, y = prop)) +
      geom_col()
  })
}

shinyApp(ui = ui, server = server)
编辑并运行代码