Last active
March 1, 2019 15:46
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Examples
To plot a horizontal color bar, ranging from 0 to 100, with the viridis color palette:
To add a black border:
To plot the color bar vertically: