Skip to content

Instantly share code, notes, and snippets.

@daattali
Last active March 7, 2016 12:53
Show Gist options
  • Select an option

  • Save daattali/4ca56bec60206311c997 to your computer and use it in GitHub Desktop.

Select an option

Save daattali/4ca56bec60206311c997 to your computer and use it in GitHub Desktop.
Find the R built-in colour that's closest in RGB space to a given colour
# Find the R built-in colour that's closest in RGB space to a given colour
# This can be useful if you have a colour in mind you want to use in your R
# code, but would rather use a pretty built-in name rather than a HEX value.
#
# @param target The target RGB colour, given as a length-3 numeric vector
# @param n The number of top hits to return
# @param superset A vector with all possible colour names to choose from
#
# Note that the closest colour in RGB space is not guaranteed to be the
# closest colour visually, but it works in many cases.
#
# @examples
# closest_colour(c(100, 100, 100)) -> "gray39"
# closest_colour(c(0, 230, 0), 3) -> "green2" "green" "green1"
# closest_colour(c(240, 150, 30)) -> "goldenrod2"
# closest_colour(col2rgb("red"), 3) -> "red" "red1" "red2"
library(magrittr)
closest_colour <- function(target, n = 1, superset = colours()) {
target %<>% as.numeric
# Find the manhattan distance from each colour to the target colour
superset %>%
col2rgb %>%
subtract(target) %>%
apply(2, function(x) x %>% abs %>% sum) %>%
order %>%
.[1:n] %>%
superset[.]
}
# This version takes HEX colours instead of RGB vectors, and can
# deal with multiple colour inputs.
# @examples
# closest_colour_hex(c("#ff0010", "#f1f1f1")) -> c("red", "gray94")
closest_colour_hex <- function(targets, n = 1, superset = colours()) {
vapply(targets, function(target) {
target <- target %>% col2rgb %>% as.numeric
# Find the manhattan distance from each colour to the target colour
superset %>%
col2rgb %>%
subtract(target) %>%
apply(2, function(x) x %>% abs %>% sum) %>%
order %>%
.[1:n] %>%
superset[.]
}, character(n))
}
@lgatto

lgatto commented Nov 7, 2015

Copy link
Copy Markdown

Very useful, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment