開始使用免費開始

變更點大小:數值輸入

數值輸入有一些文字輸入沒有的額外引數,例如 minmax,用來設定可選擇的最小與最大數值。

請注意,當在 server 端程式碼中存取輸入值時,Shiny 會自動辨識使用的是哪一種輸入元件,並回傳對應型別的物件。這表示如果你有一個 ID 為「foo」的數值輸入,則 input$foo 會回傳數值。

本練習屬於課程

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

檢視課程

練習說明

已提供上一個練習的 Shiny 應用程式程式碼。你的任務是新增一個數值輸入,讓使用者可以調整圖上點的大小。具體來說:

  • 在 UI 中新增一個數值輸入,ID 為「size」、標籤為「Point size」、預設值為 1、最小值為 1。
  • 在 server 中加入程式碼,讓這個數值輸入能決定圖中的點大小(第 20 行)。

動手互動練習

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

# Define UI for the application
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      textInput("title", "Title", "GDP vs life exp"),
      # Add a size numeric input
      ___
    ),
    mainPanel(
      plotOutput("plot")
    )
  )
)

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

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