添加用于选择年份的滑块输入
滑块输入非常适合数值型输入。无论是让用户从一个数值范围中选择,还是从一组选项中选择一个固定值,当您想比 selectInput() 更有互动性时,它都很实用。
请调整您的应用,在展示某一年前 10 个名字的基础上,添加一个滑块以选择 babynames 中可用的具体年份。
本练习是课程的一部分
使用 R 构建 Shiny Web 应用
练习说明
- 添加名为 "year" 的滑块输入,让用户可在 1900 到 2010 之间选择年份,默认值为 1900。
- 更新服务器端代码,根据所选年份获取前 10 个名字,而不是只使用 1900 年的数据。
交互式实操练习
通过完成这段示例代码来试试这个练习。
ui <- fluidPage(
titlePanel("What's in a Name?"),
# Add select input named "sex" to choose between "M" and "F"
selectInput('sex', 'Select Sex', choices = c("F", "M")),
# CODE BELOW: Add slider input named 'year' to select years (1900 - 2010)
# Add plot output to display top 10 most popular names
plotOutput('plot_top_10_names')
)
server <- function(input, output, session){
# Render plot of top 10 most popular names
output$plot_top_10_names <- renderPlot({
# Get top 10 names by sex and year
top_10_names <- babynames %>%
filter(sex == input$sex) %>%
# MODIFY CODE BELOW: Filter for the selected year
filter(year == 1900) %>%
slice_max(prop, n = 10)
# Plot top 10 names by sex and year
ggplot(top_10_names, aes(x = name, y = prop)) +
geom_col(fill = "#263e63")
})
}
shinyApp(ui = ui, server = server)