为图形添加颜色:颜色输入
colourpicker 包提供了颜色输入控件,可通过 colourInput() 函数使用。尽管颜色输入不属于 shiny 包的一部分,但它的行为与其他任何输入控件相同。
颜色输入有许多可探索的参数,但这里我们只使用基础参数:inputId、label 和 value。value 参数用于指定初始颜色。颜色可以用多种格式表示,但最简单的方式是直接使用英文颜色名称,例如 "red" 或 "yellow"。
本练习是课程的一部分
案例研究:使用 R 的 Shiny 构建 Web 应用
练习说明
已提供上一个练习中的 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)