Thêm một slider để chọn năm
Slider rất hữu ích cho dữ liệu số: vừa cho phép người dùng chọn trong một khoảng giá trị, vừa có thể chọn một giá trị cố định từ một tập tùy chọn, nhất là khi bạn muốn sáng tạo hơn thay vì dùng selectInput().
Hãy chỉnh sửa ứng dụng đang hiển thị top 10 tên theo năm bằng cách thêm một slider để chọn năm cụ thể có trong babynames.
Bài tập này là một phần của khóa học
Xây dựng ứng dụng web với Shiny trong R
Hướng dẫn bài tập
- Thêm một slider có tên "year" để người dùng chọn năm trong khoảng từ 1900 đến 2010, với giá trị mặc định là 1900.
- Cập nhật mã phía server để lấy top 10 tên cho năm được chọn thay vì chỉ năm 1900
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
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)