擬合平滑曲線:勾選方塊輸入
與文字與數值輸入不同,勾選方塊輸入只有兩種可能的值:TRUE 或 FALSE。當使用者勾選勾選方塊時,輸入值為 TRUE;若未勾選,則回傳 FALSE。
請注意,checkboxInput() 函式的 value 參數(用來設定初始值)只能設為 TRUE 或 FALSE。
本題提供上一個練習的 Shiny 應用程式碼,並做了些微調整。renderPlot() 中的 ggplot 繪圖物件現在指派給變數 p。
本練習屬於課程
案例研究:使用 R 的 Shiny 建置網頁應用程式
練習說明
你的任務是新增一個勾選方塊輸入;當被勾選時,會在圖上加入最佳擬合線。具體來說:
- 在 UI 中新增一個 ID 為「fit」、標籤為「Add line of best fit」、初始狀態為未勾選的勾選方塊輸入。
- 在伺服端加入對應的程式碼,讓當該輸入被勾選時,在圖上加入最佳擬合線。加入最佳擬合線的程式碼已提供(第 26 行)。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define UI for the application
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
textInput("title", "Title", "GDP vs life exp"),
numericInput("size", "Point size", 1, 1),
# Add a checkbox for line of best fit
___
),
mainPanel(
plotOutput("plot")
)
)
)
# Define the server logic
server <- function(input, output) {
output$plot <- renderPlot({
p <- ggplot(gapminder, aes(gdpPercap, lifeExp)) +
geom_point(size = input$size) +
scale_x_log10() +
ggtitle(input$title)
# When the "fit" checkbox is checked, add a line
# of best fit
if (___) {
p <- p + geom_smooth(method = "lm")
}
p
})
}
# Run the application
shinyApp(ui = ui, server = server)