Skip to content

Instantly share code, notes, and snippets.

@mhkeller
Forked from abelsonlive/assignColors.R
Created November 2, 2012 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhkeller/4003695 to your computer and use it in GitHub Desktop.
Save mhkeller/4003695 to your computer and use it in GitHub Desktop.
assignColors.R
# 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