พล็อตข้อมูล
กราฟเป็น output object ประเภทหนึ่ง ดังนั้นการเพิ่มกราฟลงใน Shiny app จึงต้องใช้ฟังก์ชัน plotOutput() ร่วมกับ renderPlot() โดย output function จะถูกเพิ่มใน UI เพื่อกำหนดตำแหน่งที่แสดงกราฟ ส่วน render function ในโค้ดฝั่ง server จะทำหน้าที่สร้างกราฟนั้นขึ้นมา
ในแบบฝึกหัดนี้ ให้เพิ่มกราฟแสดงความสัมพันธ์ระหว่าง GDP ต่อหัวกับอายุขัยลงในแอป ข้อมูลที่ใช้ในกราฟควรเป็นข้อมูลชุดเดียวกับที่แสดงในตาราง นั่นคือกราฟต้องแสดงเฉพาะระเบียนที่ตรงกับตัวกรองที่ผู้ใช้เลือก เนื่องจากโค้ดภายใน renderPlot() ไม่สามารถเข้าถึงตัวแปรที่กำหนดไว้ภายใน renderTable() ได้ จึงจำเป็นต้องคัดลอกโค้ดส่วนนั้นมาใช้ซ้ำโดยตรง ในบทต่อไปเราจะได้เรียนรู้วิธีหลีกเลี่ยงการเขียนโค้ดซ้ำแบบนี้
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R
คำแนะนำการฝึกหัด
- เพิ่มพื้นที่สำหรับแสดงกราฟใน UI โดยกำหนด ID ว่า "plot"
- ในฝั่ง server ใช้ render function ที่เหมาะสมเพื่อสร้างกราฟ (บรรทัดที่ 30)
- นำโค้ดกรองข้อมูลเดียวกับที่ output table ใช้มาใช้สำหรับข้อมูลในกราฟด้วย (บรรทัดที่ 32)
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
ui <- fluidPage(
h1("Gapminder"),
sliderInput(inputId = "life", label = "Life expectancy",
min = 0, max = 120,
value = c(30, 50)),
selectInput("continent", "Continent",
choices = c("All", levels(gapminder$continent))),
# Add a plot output
___(___),
tableOutput("table")
)
server <- function(input, output) {
output$table <- renderTable({
data <- gapminder
data <- subset(
data,
lifeExp >= input$life[1] & lifeExp <= input$life[2]
)
if (input$continent != "All") {
data <- subset(
data,
continent == input$continent
)
}
data
})
# Create the plot render function
output$plot <- ___({
# Use the same filtered data code that the table uses
data <- ___
___
___
ggplot(data, aes(gdpPercap, lifeExp)) +
geom_point() +
scale_x_log10()
})
}
shinyApp(ui, server)