Skip to content

Instantly share code, notes, and snippets.

@srgorelik
Last active March 1, 2019 15:46
Show Gist options
  • Save srgorelik/4e0fabff1d7eba8993c5cefe1ece967c to your computer and use it in GitHub Desktop.
Save srgorelik/4e0fabff1d7eba8993c5cefe1ece967c to your computer and use it in GitHub Desktop.
For plotting a color bar by itself. Adapted from http://www.colbyimaging.com/wiki/statistics/color-bars.
colorbar <- function(pal, min, max = -min, nticks = 11, at = seq(min, max, len = nticks), title = '', border = NA, dir = 'v') {
scale = (length(pal)-1)/(max-min)
graphics.off()
if (dir == 'v') {
w <- 1; h <- 5
xx <- c(0, 10)
yy <- c(min, max)
asp <- 2
side <- 4
} else if(dir == 'h') {
w <- 5; h <- 1
xx <- c(min, max)
yy <- c(0, 10)
asp <- 0.5
side <- 1
} else {
stop("dir must either be 'v' (vertical) or 'h' (horizontal).")
}
dev.new(width = w, height = h)
plot(xx, yy, type = 'n', bty = 'n', xaxt = 'n', xlab = '', yaxt = 'n', ylab = '', main = title, asp = asp)
axis(side = side, at = at, las = 1, pos = 5, col = NA, col.ticks = NA)
for (i in 1:(length(pal)-1)) {
if (dir == 'v') { y = (i-1)/scale + min; rect(0, y, 10, y+1/scale, col = pal[i], border = NA) }
if (dir == 'h') { x = (i-1)/scale + min; rect(x, 0, x+1/scale, 10, col = pal[i], border = NA) }
}
if (dir == 'v') rect(0, 0, 10, y+1/scale, col = NA, border = border)
if (dir == 'h') rect(0, 0, x+1/scale, 10, col = NA, border = border)
}
@srgorelik
Copy link
Author

srgorelik commented Mar 1, 2019

Examples

To plot a horizontal color bar, ranging from 0 to 100, with the viridis color palette:

colorbar(pal = viridis::inferno(256), min = 0, max = 100, nticks = 6, dir = 'h')

To add a black border:

colorbar(pal = viridis::inferno(256), min = 0, max = 100, nticks = 6, border = 'black', dir = 'h')

To plot the color bar vertically:

colorbar(pal = viridis::inferno(256), min = 0, max = 100, nticks = 6, border = 'black', dir = 'v')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment