เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

เพิ่มสีให้กราฟ: color input

แพ็กเกจ colourpicker มี color input ให้ใช้งานผ่านฟังก์ชัน colourInput() แม้ว่า color input จะไม่ได้เป็นส่วนหนึ่งของแพ็กเกจ shiny โดยตรง แต่ก็ทำงานในลักษณะเดียวกับ input ประเภทอื่นทุกประการ

color input มีอาร์กิวเมนต์หลายตัวให้ลองใช้งาน แต่ในที่นี้จะใช้เฉพาะอาร์กิวเมนต์พื้นฐาน ได้แก่ inputId, label, และ value อาร์กิวเมนต์ value รับค่าสีที่ต้องการใช้เป็นค่าเริ่มต้น ระบุสีได้หลายรูปแบบ แต่วิธีที่ง่ายที่สุดคือใช้ชื่อสีภาษาอังกฤษ เช่น "red" หรือ "yellow"

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R

ดูคอร์ส

คำแนะนำการฝึกหัด

โค้ดของ Shiny app จากแบบฝึกหัดที่แล้วได้เตรียมไว้ให้แล้ว ให้แทนที่ radio button ที่ใช้เลือกสีด้วย color input โดยทำตามขั้นตอนต่อไปนี้

  • โหลดแพ็กเกจ colourpicker
  • หาฟังก์ชัน UI ที่สร้าง radio button สำหรับเลือกสี แล้วแทนที่ด้วย color input (บรรทัดที่ 12)
  • color input ควรมี ID ว่า "color", label ว่า "Point color", และสีเริ่มต้นเป็น "blue"

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# Load the colourpicker package
___

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),

      # Replace the radio buttons with a color input
      radioButtons("color", "Point color",
                   choices = c("blue", "red", "green", "black")),
      selectInput("continents", "Continents",
                  choices = levels(gapminder$continent),
                  multiple = TRUE,
                  selected = "Europe"),
      sliderInput("years", "Years",
                  min(gapminder$year), max(gapminder$year),
                  value = c(1977, 2002))
    ),
    mainPanel(
      plotOutput("plot")
    )
  )
)

# Define the server logic
server <- function(input, output) {
  output$plot <- renderPlot({
    data <- subset(gapminder,
                   continent %in% input$continents &
                   year >= input$years[1] & year <= input$years[2])
    
    p <- ggplot(data, aes(gdpPercap, lifeExp)) +
      geom_point(size = input$size, col = input$color) +
      scale_x_log10() +
      ggtitle(input$title)
    
    if (input$fit) {
      p <- p + geom_smooth(method = "lm")
    }
    p
  })
}

shinyApp(ui = ui, server = server)
แก้ไขและรันโค้ด