開始使用免費開始

你的第一個 shinyApp

你已經看過如何在 shinyApp 中組合輸入與輸出。你也看過如何建立一個 shinyApp 來呈現睡眠研究的結果。

你現在的目標是建立一個 shinyApp,回報兩個主要結果:

  1. 睡眠時數的分布
  2. 不同年齡族群的睡眠時數中位數

在這個練習中,我們已經將資料以 dplyr 資料框的形式存成 sleep,而且已經載入 shinytidyverse 套件。

現在換你來建立自己的 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
___
編輯並執行程式碼