你的第一個 shinyApp
你已經看過如何在 shinyApp 中組合輸入與輸出。你也看過如何建立一個 shinyApp 來呈現睡眠研究的結果。
你現在的目標是建立一個 shinyApp,回報兩個主要結果:
- 睡眠時數的分布
- 不同年齡族群的睡眠時數中位數
在這個練習中,我們已經將資料以 dplyr 資料框的形式存成 sleep,而且已經載入 shiny 與 tidyverse 套件。
現在換你來建立自己的 shinyApp!
本練習屬於課程
使用 shinydashboard 建立儀表板
練習說明
- 在
mainPanel中加入兩個圖表輸出,名稱分別為「histogram」與「barchart」。 - 在
checkboxGroupInput()的choiceNames參數中,將內容替換為名為「calendar」、 「briefcase」與「gift」的圖示。 - 定義兩個輸出,一個名為
histogram,另一個名為barchart。 - 使用
shinyApp()函式來渲染這個 shiny 應用。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
ui <- fluidPage(
titlePanel("Sleeping habits in America"),
fluidRow(
# Place two plots here, called "histogram" and "barchart"
mainPanel(___("histogram"), ___("barchart")),
inputPanel(sliderInput("binwidth",
label = "Bin width",
min = 0.1, max = 2,
step = 0.01, value=0.25),
checkboxGroupInput("days", "Choose types of days:",
# Replace the list elements with icons called "calendar", "briefcase" and "gift"
choiceNames = list("All days",
"Non-holiday weekdays",
"Weekend days/holidays"),
choiceValues = list("All days",
"Nonholiday weekdays",
"Weekend days and holidays"))),
"In general, across the different age groups, Americans seem to get adequate daily rest." ))
server <- function(input, output, session) {
# Define the histogram and barchart
output$histogram <- ___({
ggplot(sleep, aes(x=`Avg hrs per day sleeping`)) +
geom_histogram(binwidth = input$binwidth, col='white') +
theme_classic()
})
___ <- ___({
filter(sleep, `Type of Days` %in% input$days) %>%
group_by(`Type of Days`, `Age Group`) %>%
summarize(`Median hours` = median(`Avg hrs per day sleeping`)) %>%
ggplot(aes(x = `Median hours`, y = `Age Group`, fill = `Type of Days`)) +
geom_col(position = 'dodge') + theme_classic()
})
}
# Use shinyApp() to render the shinyApp
___