開始使用免費開始

繪製資料圖

記得圖形屬於輸出物件,因此需要搭配 plotOutput() + renderPlot() 這組函式加入 Shiny 應用程式。輸出函式加在 UI,用來決定圖形放在哪裡;伺服端的 render 函式則負責產生圖形。

你的任務是替應用程式加入一張以人均 GDP 對壽命的散佈圖。此圖所用的資料必須與表格顯示的資料相同;也就是說,圖中只應顯示符合輸入篩選條件的紀錄。renderPlot() 內的程式碼無法存取定義在 renderTable() 內的變數,所以你需要直接複製並重用相同的程式碼。之後我們會學到如何避免這種重複。

本練習屬於課程

案例研究:使用 R 的 Shiny 建置網頁應用程式

檢視課程

練習說明

  • 在 UI 中加入一個圖形輸出的佔位元,ID 設為「plot」。
  • 在伺服端第 30 行,使用合適的 render 函式來建立圖形。
  • 在第 32 行,重用輸出表格所使用的資料篩選程式碼,作為圖形的資料。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

ui <- fluidPage(
  h1("Gapminder"),
  sliderInput(inputId = "life", label = "Life expectancy",
              min = 0, max = 120,
              value = c(30, 50)),
  selectInput("continent", "Continent",
              choices = c("All", levels(gapminder$continent))),
  # Add a plot output
  ___(___),
  tableOutput("table")
)

server <- function(input, output) {
  output$table <- renderTable({
    data <- gapminder
    data <- subset(
      data,
      lifeExp >= input$life[1] & lifeExp <= input$life[2]
    )
    if (input$continent != "All") {
      data <- subset(
        data,
        continent == input$continent
      )
    }
    data
  })

  # Create the plot render function  
  output$plot <- ___({
    # Use the same filtered data code that the table uses
    data <- ___
            ___
            ___
    ggplot(data, aes(gdpPercap, lifeExp)) +
      geom_point() +
      scale_x_log10()
  })
}

shinyApp(ui, server)
編輯並執行程式碼