เพิ่มชื่อกราฟ: text input
ใน Shiny เมื่อผู้ใช้เปลี่ยนค่า input ใดก็ตาม Shiny จะนำค่าปัจจุบันนั้นส่งไปยังฝั่ง server ผ่านอาร์กิวเมนต์ input ของฟังก์ชัน server ทันที สามารถดึงค่าของ input แต่ละตัวได้ด้วย input$<inputId>
หากต้องการกำหนดค่าเริ่มต้นให้กับ text input ให้ใช้อาร์กิวเมนต์ value
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R
คำแนะนำการฝึกหัด
แอป Shiny ที่กำหนดให้นี้จะพล็อตกราฟ GDP per capita เทียบกับอายุขัยเฉลี่ยของประเทศต่างๆ ในชุดข้อมูล gapminder โดยมีโจทย์ให้เพิ่ม text input เพื่อให้ผู้ใช้สามารถเปลี่ยนชื่อกราฟได้ ดังนี้
- เพิ่ม text input ใน UI โดยกำหนด ID เป็น "title", ป้ายกำกับเป็น "Title", และค่าเริ่มต้นเป็น "GDP vs life exp"
- ในโค้ดฝั่ง server ให้ชื่อกราฟสะท้อนค่าปัจจุบันของ input
titleเสมอ โดยวางค่าดังกล่าวไว้ในฟังก์ชัน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)