開始使用免費開始

加入圖表標題:文字輸入

在 Shiny 中,只要使用者變更任何輸入的值,Shiny 就會立即透過伺服端函式的 input 引數,讓你存取該輸入的當前值。你可以用 input$<inputId> 取得任何輸入的值。

若要為文字輸入框指定預設初始值,請使用 value 參數。

本練習屬於課程

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

檢視課程

練習說明

提供的 Shiny 應用會繪製 gapminder 資料集中各國的 GDP per capita 與 life expectancy 的散佈圖。你的任務是新增一個文字輸入,讓使用者可以更改圖表標題。具體來說:

  • 在 UI 中新增一個文字輸入,ID 為「title」、標籤為「Title」、預設值為「GDP vs life exp」。
  • 在伺服端程式碼中,將圖表標題放入 ggtitle() 函式(第 24 行),使其永遠反映目前的標題輸入值。

動手互動練習

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

# Load the ggplot2 package for plotting
library(ggplot2)

# Define UI for the application
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      # Add a title text input
      ___(___, ___, ___)
    ),
    mainPanel(
      plotOutput("plot")
    )
  )
)

# Define the server logic
server <- function(input, output) {
  output$plot <- renderPlot({
    ggplot(gapminder, aes(gdpPercap, lifeExp)) +
      geom_point() +
      scale_x_log10() +
      # Use the input value as the plot's title
      ggtitle(___)
  })
}

# Run the application
shinyApp(ui = ui, server = server)
編輯並執行程式碼