Skip to content

Instantly share code, notes, and snippets.

@sklarz-bgu
Last active February 8, 2017 11:05
Show Gist options
  • Save sklarz-bgu/01a550f59cdf5bc85a48e15f5e94a6ba to your computer and use it in GitHub Desktop.
Save sklarz-bgu/01a550f59cdf5bc85a48e15f5e94a6ba to your computer and use it in GitHub Desktop.
R script for converting hex colors into closest X11 color name.
library(magrittr)
colhex2col <- function(colhex) {
# Convert hex to RGB
mycol <- colhex %>% col2rgb()
# Convert all x11 colors to RGB, adn transform
colors() %>% # Get X11 colors (hex)
col2rgb %>% # Convert to RGB matrix
data.frame %>% # Convert to data.frame
setNames(.,colors()) %>% # Set color names
t %>% # Transform so colors are in rows (columns: R,G,B)
data.frame %>% # Re-convert to data.frame
apply(.,1,function(x) sum(abs(x-mycol)) ) %>% # For each color, calc the sum of diff between mycol RGB and the color RGB
sort %>% # Sort so color with smallest diff comes first
'['(1) %>% # Get the first color in the df = closest
names %>% # Return the name of the color
return
}
# Get names of 20 rainbow colors:
lapply(rainbow(20),colhex2col) %>% unlist %>% paste(.,collapse=" ")
# Get names of 8 Pastel2 colors from RColorBrewer:
lapply(RColorBrewer::brewer.pal(8, "Pastel2"),colhex2col) %>% unlist %>% paste(.,collapse=" ")
# Visualization:
plot(1:50,
pch = 20,
cex = 2,
col = rainbow(50))
points(1:50,
2+(1:50),
pch = 20,
cex = 2,
col = lapply(rainbow(50),colhex2col) %>% unlist)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment