Skip to content

Instantly share code, notes, and snippets.

@sdtaylor
Last active September 20, 2019 17:44
Show Gist options
  • Select an option

  • Save sdtaylor/9e091105f18f87bd3c45569c8f4e98df to your computer and use it in GitHub Desktop.

Select an option

Save sdtaylor/9e091105f18f87bd3c45569c8f4e98df to your computer and use it in GitHub Desktop.
Generate discrete color values for numerous categories (>10)
library(ggplot2)
# Make a vector of colors of size n based on an RColorBrewer palette
# or list of colors.
get_extended_palette = function(original_palette = 'Paired', n){
brewer_palettes = rownames(RColorBrewer::brewer.pal.info)
if(length(original_palette)>=2){
original_palette_values = original_palette
} else if(original_palette %in% brewer_palettes){
original_palette_values = RColorBrewer::brewer.pal(9, original_palette) # most of the palettes have 9 colors to start with
} else {
stop('Unknown palette name')
}
generate_palette = colorRampPalette(original_palette_values)
generate_palette(n)
}
color_count = 20
# Pass in a brewer palette which serves as a base for colors generated.
palette = sample(get_extended_palette(original_palette = 'Set1',n=color_count))
tibble(x=1:color_count) %>%
ggplot() +
geom_vline(aes(xintercept = x, color=as.factor(x)), size=5) +
scale_color_manual(values = palette) +
theme(legend.position = 'none')
# Or pass in a list of colors to start with instead.
palette = sample(get_extended_palette(original_palette = c('gold','black','green4','violetred'),n=color_count))
tibble(x=1:color_count) %>%
ggplot() +
geom_vline(aes(xintercept = x, color=as.factor(x)), size=5) +
scale_color_manual(values = palette) +
theme(legend.position = 'none')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment