Skip to content

Instantly share code, notes, and snippets.

@erichare
Created July 25, 2018 13:11
Show Gist options
  • Save erichare/5f6bf1f70c04ac55368d0205cc99119d to your computer and use it in GitHub Desktop.
Save erichare/5f6bf1f70c04ac55368d0205cc99119d to your computer and use it in GitHub Desktop.
Get a ggplot2 color scheme based on the RGB pixel values of an image/logo
# Sets theme according to color of logo
set_color_theme <- function(logo_loc, low_sat = 0.042, high_sat = 0.866, medium_sat = 0.28,
low_val = 0.99, high_val = 0.38, medium_val = 0.65) {
# Read image/logo as a list
img1 <- list(readPNG(file.path(logo_loc)))
# Find the average pixel value
rgb <- rowMeans(sapply(img1, function(im) apply(im, 3, mean) * 255))
# Convert to HSV - hue, saturation, value
img_hsv <- rgb2hsv(rgb[1:3])[,1]
# Plot theme - Keeping the hue(color) values the same, saturation (purity) and value (dark/light) are increased or decreased.
# lighter color for the plot background
bckgrnd_color <- hsv2rgb(img_hsv[1] * 360, min(low_sat, img_hsv[2]), max(low_val, img_hsv[3]))
# darker color for the axis labels/text
label_color <- hsv2rgb(img_hsv[1] * 360, max(high_sat, img_hsv[2]), min(high_val, img_hsv[3]))
# middle color for lines/points on plot
points_color <- hsv2rgb(img_hsv[1] * 360, min(medium_sat, img_hsv[2]), ifelse(img_hsv[3] < 0.5, 0.5, min(medium_val, img_hsv[3])))
return(list("img_rgb" = rgb(rgb[1], rgb[2], rgb[3], maxColorValue = 255), "bckgrnd_color" = bckgrnd_color, "label_color" = label_color, "points_color" = points_color))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment