duttashi / visualizer

My experiments in data visualizations. Feel free to show your :heart: by giving a star :star:

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to create a color palette in R with more than 15 colors with ggplot2

duttashi opened this issue · comments

This question was originally asked on StackOverflow

I'm reproducing it here for any future reference

Use the library RColorBrewer for attractive palettes and colorRamps for easy construction of color palettes.

When using the library ggplot2, a simple visualization can be made from the variables in the data, for example, consider the following code snippet;

library (ggplot2)
ggplot(mtcars) +
  geom_histogram(aes(factor(cyl), fill=factor(cyl)), stat = "count")

This code snippet will generate a plot with a default color scheme (light blue to dark blue colors). Now, this can be changed by adding the code scale_fill_brewer(palette = "Set1") like;

ggplot(mtcars) +
  geom_histogram(aes(factor(cyl), fill=factor(cyl)), stat = "count") +
  scale_fill_brewer(palette = "Set1")

Now, palettes live in the package RColorBrewer - to see all available choices simply attach the package with library (RColorBrewer) and run display.brewer.all() to show a list of available palettes.

There are 3 types of palettes, sequential, diverging, and qualitative.

  1. Sequential palettes are suited to ordered data that progress from low to high. Lightness steps dominate the look of these schemes, with light colors for low data values to dark colors for high data values.
  2. Diverging palettes put equal emphasis on mid-range critical values and extremes at both ends of the data range. The critical class or break in the middle of the legend is emphasized with light colors and low and high extremes are emphasized with dark colors that have contrasting hues.
  3. Qualitative palettes do not imply magnitude differences between legend classes, and hues are used to create the primary visual differences between classes. Qualitative schemes are best suited to representing nominal or categorical data. See ?RColorBrewer for more information

Now, to answer the question, the code is given below;

## Required packages
library(ggplot2)
library(RColorBrewer)
library(colorRamps)

## Data
data(mtcars)

## See available palettes
display.brewer.all()

## You need to expand palette size
colourCount <- length(unique(mtcars$hp)) # number of levels
getPalette <- colorRampPalette(brewer.pal(9, "Set1"))

## Now you can draw your 15 different factors
g <- ggplot(mtcars) 
g <- g +  geom_bar(aes(factor(hp), fill=factor(hp))) 
g <- g +  scale_fill_manual(values = colorRampPalette(brewer.pal(12, 
                                                                 "Accent"))(colourCount)) 
g <- g + theme(legend.position="top")
g <- g + xlab("X axis name") + ylab("Frequency (%)")
g