เพิ่ม CSS เพื่อปรับแต่งหน้าตาของแอป
CSS เป็นภาษา markup ที่ได้รับความนิยมสูง ใช้สำหรับบอกเบราว์เซอร์ว่าจะแสดง element ต่าง ๆ บนหน้าเพจอย่างไร หากต้องการปรับแต่งรูปลักษณ์ของแอป Shiny ให้ต่างจากค่าเริ่มต้น จำเป็นต้องใช้ CSS
ทบทวนกันอีกครั้ง CSS ประกอบด้วยชุดของกฎ โดยแต่ละกฎเป็นคู่ property: value ที่กำหนดให้กับ element บนหน้าเพจ วิธีหนึ่งในการใส่ CSS ลงในแอปคือเขียนไว้ในไฟล์แยกต่างหากแล้วนำเข้าด้วย includeCSS() แต่ในคอร์สนี้จะใช้วิธีที่ง่ายกว่า คือวางโค้ด CSS ไว้ใน tags$style() ใน UI โดยตรง
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R
คำแนะนำการฝึกหัด
- เขียนกฎ CSS เพื่อปรับแต่งแอปในลักษณะต่อไปนี้:
- เปลี่ยนสีพื้นหลังของปุ่มดาวน์โหลดเป็นสีส้ม (บรรทัดที่ 5)
- เปลี่ยนขนาดตัวอักษรของปุ่มดาวน์โหลดเป็น 20 พิกเซล (บรรทัดที่ 8)
- เปลี่ยนสีตัวอักษรของตารางเป็นสีแดง (บรรทัดที่ 13)
- เพิ่มกฎ CSS เหล่านี้ลงในแอป Shiny (บรรทัดที่ 20)
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
my_css <- "
#download_data {
/* Change the background color of the download button
to orange. */
background: ___;
/* Change the text size to 20 pixels. */
font-size: ___px;
}
#table {
/* Change the text color of the table to red. */
color: ___;
}
"
ui <- fluidPage(
h1("Gapminder"),
# Add the CSS that we wrote to the Shiny app
tags$style(___),
tabsetPanel(
tabPanel(
title = "Inputs",
sliderInput(inputId = "life", label = "Life expectancy",
min = 0, max = 120,
value = c(30, 50)),
selectInput("continent", "Continent",
choices = c("All", levels(gapminder$continent))),
downloadButton("download_data")
),
tabPanel(
title = "Plot",
plotOutput("plot")
),
tabPanel(
title = "Table",
DT::dataTableOutput("table")
)
)
)
server <- function(input, output) {
filtered_data <- reactive({
data <- gapminder
data <- subset(
data,
lifeExp >= input$life[1] & lifeExp <= input$life[2]
)
if (input$continent != "All") {
data <- subset(
data,
continent == input$continent
)
}
data
})
output$table <- DT::renderDataTable({
data <- filtered_data()
data
})
output$download_data <- downloadHandler(
filename = "gapminder_data.csv",
content = function(file) {
data <- filtered_data()
write.csv(data, file, row.names = FALSE)
}
)
output$plot <- renderPlot({
data <- filtered_data()
ggplot(data, aes(gdpPercap, lifeExp)) +
geom_point() +
scale_x_log10()
})
}
shinyApp(ui, server)