Add colours to your plot: color input
The colourpicker
package provides a color input, available through the colourInput()
function. Even though color inputs are not part of the shiny package, they behave in the same way as any other input.
A color input can have many different arguments you can explore, but we will only use the basic arguments: inputId
, label
, and value
. The value
argument accepts a color to use as the initial value. Colours can be specified in several different formats, but the easiest one is to simply use English color names such as "red" or "yellow".
This exercise is part of the course
Case Studies: Building Web Applications with Shiny in R
Exercise instructions
The code for the Shiny app from the last exercise is provided. Your task is to replace the radio buttons that are used to select a color with a color input. Specifically:
- Load the
colourpicker
package. - Find the UI function that creates the radio buttons that are used for selecting a colour, and replace it with a color input (line 12).
- The color input should have ID "color", a label of "Point color", and a default color of "blue".
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# 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)