開始使用免費開始

將不同輸出放在不同分頁

當內容太多需要分段呈現時,分頁很有用。要建立分頁,只要把 UI 元素包在 tabPanel() 函式裡,並透過 title 參數提供分頁標題。

為了讓分頁顯示在 UI 中,必須把多個分頁面板放進一個分頁組「容器」,也就是把所有分頁面板包在 tabsetPanel() 裡。

你的任務是為這個 Shiny 應用程式加入分頁,讓輸入元件與下載按鈕在同一個分頁,圖形在另一個分頁,表格在第三個分頁。由於這只是視覺上的調整,所有程式碼變更都只需在 UI 區塊進行。

本練習屬於課程

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

檢視課程

練習說明

  • 使用 tabsetPanel() 函式建立一個包含三個分頁面板的容器:
    • 第一個分頁放輸入元件,並將分頁命名為「Inputs」。
    • 第二個分頁顯示圖形,並將分頁命名為「Plot」(第 16 行)。
    • 第三個分頁顯示表格,並將分頁命名為「Table」(第 21 行)。

動手互動練習

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

ui <- fluidPage(
    h1("Gapminder"),
    # Create a container for tab panels
    ___(
        # Create an "Inputs" tab
        tabPanel(
            title = ___,
            sliderInput(inputId = "life", label = "Life expectancy",
                        min = 0, max = 120,
                        value = c(30, 50)),
            selectInput("continent", "Continent",
                        choices = c("All", levels(gapminder$continent))),
            downloadButton("download_data")
        ),
        # Create a "Plot" tab
        ___(
            title = "Plot",
            plotOutput("plot")
        ),
        # Create "Table" tab
        ___(
            title = ___,
            DT::dataTableOutput("table")
        )
    )
)

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

  output$download_data <- downloadHandler(
    filename = "gapminder_data.csv",
    content = function(file) {
      data <- filtered_data()
      write.csv(data, file, row.names = FALSE)
    }
  )

  output$plot <- renderPlot({
    data <- filtered_data()
    ggplot(data, aes(gdpPercap, lifeExp)) +
      geom_point() +
      scale_x_log10()
  })
}

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