Skip to content

Instantly share code, notes, and snippets.

@rasmusab
Created June 18, 2016 10:11
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rasmusab/2ddd12eb67e9019dd1f16bbaf5935786 to your computer and use it in GitHub Desktop.
Save rasmusab/2ddd12eb67e9019dd1f16bbaf5935786 to your computer and use it in GitHub Desktop.
A function that takes a vector of color names and matches it against the xkcdcolors list of color names using edit distance.
# fuzzycolor() takes a vector of color names and matches it against the
# xkcdcolors list of color names using edit distance. fuzzycolor() always
# returns a vector of hex color strings, perhaps the ones you wanted...
fuzzycolor <- function(color_names) {
library(xkcdcolors)
names_distance <- adist(color_names, xcolors(), ignore.case = TRUE, partial = TRUE)
xkcd_colors <- xcolors()[ apply(names_distance, 1, which.min) ]
hex_colors <- name2color(xkcd_colors)
names(hex_colors) <- xkcd_colors
hex_colors
}
# Here's how you can use it
cols <- fuzzycolor(c("red", "darkerred", "minty fresh", "North sea", "spinach"))
cols
#+ fig.height=3, fig.width=9
barplot(rep(1, length(cols)), names.arg = names(cols), col = cols)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment