Last active
August 29, 2015 13:55
-
-
Save jakob-r/8698461 to your computer and use it in GitHub Desktop.
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
# Author: Jakob Richter (https://gist.github.com/jakob-r) | |
# colfuncMiddle does the same as colfunc but gives respect to middle point. | |
# usage: x : numeric() | |
# colfunc: function generated by colorRampPalette() | |
# zeropoint: numeric(1) | |
colfuncMiddle = function(x, colfunc, n, zeropoint=0){ | |
stopifnot(is.numeric(x) | is.factor(x)) | |
if(!missing(n)){ | |
stopifnot(length(n)==1) | |
stopifnot(n>0) | |
} | |
if(is.factor(x)) { | |
n = length(levels(x)) | |
x = as.numeric(x) | |
} | |
givenRange = range(x, na.rm=TRUE) | |
neededRange = c(-1,1) * max(abs(zeropoint-givenRange)) + zeropoint | |
neededBreaks = ceiling(diff(neededRange)/diff(givenRange) * n) | |
myPalette = colfunc(n=neededBreaks) | |
if((neededRange - givenRange)[1]==0){ | |
myPalette = head(myPalette, n) | |
}else{ | |
myPalette = tail(myPalette, n) | |
} | |
myPalette | |
} | |
# # Example: | |
# nbreaks = 10 | |
# zeropoint = 0 | |
# colfunc = colorRampPalette(c("green","white","red"), space = c("Lab")) | |
# x = runif(100,min=-5,max=10) | |
# myPalette = colfuncMiddle(x, colfunc, nbreaks, zeropoint) | |
# cutted = cut(x, breaks=nbreaks) | |
# barplot(table(cutted), col=myPalette) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment