A Shiny app for creating custom color bars

There has been a few odd times that I’ve needed to create a custom color bar for my figures. A really simple solution in R can be found here. Although running this in R is easy enough, one idea I had was to turn this task into an interactive Shiny app. So here it is… introducing Colour Bar Builder, a Shiny app for creating custom colour bars interactively. A demo is available on shinyapps.io.

Putting together a functional app was quick and easy, as all I had to do was to create the Shiny interface. In addition to the existing R function, another key component that made this app possible was the colourInput() input control provided by shinyjs. This provides the user an interactive control for choosing colours in one line of code:

colourInput("colour", "Select colour:", value = "blue")

To create a colour bar, three base colours that define the gradient are required (the Shiny app uses three, but the function can accept as many as you want used in R). A colour ramp palette using colorRampPalette() is then created based on these selected colours. The amount of colours in the gradient can be controlled using the slider. I also added the option to choose from any of the colourblind friendly RColorBrewer sequential and diverging palettes. Other optional parameters can also be customized, such as the minimum and maximum values for the y-axis, title, and number of ticks. Taken together, the plot code in server.R looks like the following:

color.bar(
	colorRampPalette(c(input$lo, input$mid, input$hi))(input$numColours),
	min = input$min, max=input$max,
	nticks = input$nticks,
	title = input$title)

Screenshot

Saving the colour bar

The generated colour bar can then be saved by right-clicking on the image, or saving it as a PDF. The latter was made possible by adding a download handler. In ui.R, I added a download button called "savepdf":

downloadButton("savepdf", label = "Download PDF")

Next, in server.R, I just had to program the action of the download button:

1
2
3
4
5
6
7
8
9
10
11
12
output$savepdf <- downloadHandler(
	filename = "colorbar.pdf",
	content = function(file) {
	  pdf(file, height=4, width=2)
	  color.bar(
		colorRampPalette(c(input$lo, input$mid, input$hi))(input$numColours),
		min = input$min, max=input$max,
		nticks = input$nticks,
		title = input$title)
	  dev.off()
	}
)

Here, the arguments filename and content handle the default filename to use when saving the PDF and what to save, respectively.