開始使用免費開始

為你的圖形加上顏色:單選按鈕

當你要提供多個選項並要求使用者擇一時,會用到單選按鈕。它有一個 choices 參數,用來定義使用者可選的不同選項;還有一個 selected 參數,用來定義一開始預設選到哪一個。請注意,沒有 value 參數,不過你可以把 selected 視為扮演了類似的角色。

本練習屬於課程

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

檢視課程

練習說明

已提供上一個練習的 Shiny 應用程式碼。你的任務是加入單選按鈕,讓使用者可以選擇繪圖要用的顏色。具體要求:

  • 在 UI 中加入 ID 為「color」、標籤為「Point color」的單選按鈕,並包含 4 個選項:「blue」、「red」、「green」、「black」。
  • 在伺服端加入程式碼,讓圖中的點會採用單選按鈕所選的顏色(第 22 行)。

動手互動練習

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

# Define UI for the application
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      textInput("title", "Title", "GDP vs life exp"),
      numericInput("size", "Point size", 1, 1),
      checkboxInput("fit", "Add line of best fit", FALSE),
      # Add radio buttons for colour
      ___("color", ___, ___)
    ),
    mainPanel(
      plotOutput("plot")
    )
  )
)

# Define the server logic
server <- function(input, output) {
  output$plot <- renderPlot({
    p <- ggplot(gapminder, aes(gdpPercap, lifeExp)) +
      # Use the value of the color input as the point colour
      geom_point(size = input$size, col = input$___) +
      scale_x_log10() +
      ggtitle(input$title)
    
    if (input$fit) {
      p <- p + geom_smooth(method = "lm")
    }
    p
  })
}

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