-
-
Save mhkeller/4003695 to your computer and use it in GitHub Desktop.
assignColors.R
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
# this function takes an input numeric vector and | |
# partitions it into a set number of breaks | |
# it then assigns a color to each break via RColorBrewer | |
assignColors <- function(var, | |
n = 9, # number of colors / breaks | |
style = "jenks", # can be changed to other methods in "classIntervals" | |
pal = "RdYlBu", # Palettes from RColorBrewer | |
na_color ='#787878', # Color to give NA's | |
na_omit = FALSE, # Logical, argument above will be irrelevant if TRUE | |
alph=0.5 # Opacity (0-1) | |
) { | |
# load required libraries | |
require("classInt") | |
require("scales") | |
require("RColorBrewer") | |
require("plyr") | |
# na_omit? | |
if (na_omit) { | |
var <- var[!is.na(var)] | |
} | |
# create colors | |
cols <- brewer.pal(n, pal) | |
# create breaks | |
cuts <- classIntervals(var, n, style=style) | |
breaks <- cut(var, breaks=cuts$brks, labels=FALSE) | |
# create function | |
assignColor <- function(x) { | |
if(is.na(x)) { | |
assignment <- alpha(na_color, alph) | |
} else { | |
assignment <- alpha(cols[x], alph) | |
} | |
return(assignment) | |
} | |
# assign colors to breaks | |
assignments <- unlist(llply(breaks, assignColor, .progress="text")) | |
return(assignments) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment