新增可選年份的滑桿輸入
滑桿輸入很適合處理數值型輸入。不論是要讓使用者從一段範圍中選值,或是從一組固定選項中選擇單一數值,當你想比 selectInput() 更有互動感時,都是好選擇。
請調整你的應用程式,為顯示某一年度前 10 名名字的圖表加入一個滑桿,讓使用者能選擇 babynames 中可用的特定年份。
本練習屬於課程
使用 R 的 Shiny 建立網頁應用程式
練習說明
- 新增一個名為「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)