為你的圖形加入顏色:color input
colourpicker 套件提供了色彩輸入元件,可透過 colourInput() 函式使用。雖然色彩輸入不是 shiny 套件的一部分,但它的行為和其他輸入元件相同。
色彩輸入有許多參數可探索,不過這裡只會使用基本參數:inputId、label 與 value。value 參數接受一個顏色作為初始值。顏色可用多種格式指定,但最簡單的方式是直接使用英文色名,例如「red」或「yellow」。
本練習屬於課程
案例研究:使用 R 的 Shiny 建置網頁應用程式
練習說明
已提供上一個練習中的 Shiny 應用程式程式碼。你的任務是把用來選擇顏色的單選按鈕改成色彩輸入。具體來說:
- 載入
colourpicker套件。 - 找出在 UI 中建立用來選擇顏色的單選按鈕的函式,並將它改成色彩輸入(第 12 行)。
- 色彩輸入的 ID 應為「color」,標籤為「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)