Notes P

Pretty Documents: Colors, Themes, and Scales

#LOAD PACKAGES
library(tidyverse)

Themes

If you want to set your ggplot theme globally (for the whole document) you can use this code:

theme_set(theme_minimal())

Digits

Colors

Default Colors

bp <- ggplot(iris, aes(Species, Sepal.Length)) + 
  geom_boxplot(aes(fill = Species)) +
  theme_minimal() +
  theme(legend.position = "top")
bp

# Scatter plot
sp <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + 
  geom_point(aes(color = Petal.Length)) +
  theme_minimal()+
  theme(legend.position = "top")
sp

Boxplot Plot – discrete colors

Scatterplot – continuous colors

Default Colors

On a plot

For a plot you can create a custom color palette:

color fill
This will be applied to points, lines and texts This will change the fill color of areas, such as in box plot, bar plot, histogram, density plots, etc.
discrete scale_color_manual scale_fill_manual
continuous scale_color_gradient scale_fill_gradient
want continuous from discrete scale scale_color_distill scale_fill_distill
bp
bp + 
  scale_fill_manual(values=c("#9966cc", "#005bac", "#d50032"))
sp 
sp +
  scale_colour_gradient(low = "yellow", high = "red")

Color Palettes: colorBrewer

The RColorBrewer package creates a nice looking color palettes.

library(RColorBrewer)
display.brewer.all()

  • Sequential palettes (first list of colors), which are suited to ordered data that progress from low to high (gradient). The palettes names are : Blues, BuGn, BuPu, GnBu, Greens, Greys, Oranges, OrRd, PuBu, PuBuGn, PuRd, Purples, RdPu, Reds, YlGn, YlGnBu YlOrBr, YlOrRd.
  • Qualitative palettes (second list of colors), which are best suited to represent nominal or categorical data. They not imply magnitude differences between groups. The palettes names are : Accent, Dark2, Paired, Pastel1, Pastel2, Set1, Set2, Set3.
  • Diverging palettes (third list of colors), which put equal emphasis on mid-range critical values and extremes at both ends of the data range. The diverging palettes are : BrBG, PiYG, PRGn, PuOr, RdBu, RdGy, RdYlBu, RdYlGn, Spectral
bp
bp + 
  scale_fill_brewer(palette = "Dark2")
sp 
sp +
  scale_color_distiller(palette = "BuPu")

Other Cool Palettes

  • ggsci
  • wesanderson
  • tayloRswift

Global Custom Color Palettes

If you want to set your ggplot colors globally (for the whole document) you can use this code:

options(ggplot2.discrete.color= c("#9966cc", "#005bac", "#d50032", "#c9b037", "#3D424D"), 
        ggplot2.discrete.fill = c("#9966cc", "#005bac", "#d50032", "#c9b037", "#3D424D"))

Legends

hide the legend

bp
bp + 
  guides(fill="none")

customizing title of legend

sp
sp + 
  scale_color_continuous(name="Petal Length")

Axes and scales

customizing axes breaks

sp
sp + 
  scale_y_continuous(breaks=c(2,3,4,5))