Plotting and Color in R

Colors 1, 2, and 3

set.seed(19)
x <- rnorm(30)
y <- rnorm(30)
plot(x, y, col = rep(1:3, each = 10), pch = 19)
legend("bottomright", legend = paste("Group", 1:3), col = 1:3, pch = 19, bty = "n")

par(mfrow = c(1, 2))
image(volcano, col = heat.colors(10), main = "heat.colors()")
image(volcano, col = topo.colors(10), main = "topo.colors()")

Connecting colors with data

Color Utilities in R

colorRamp()

pal <- colorRamp(c("red", "blue"))

pal(0)
##      [,1] [,2] [,3]
## [1,]  255    0    0
## blue
pal(1)
##      [,1] [,2] [,3]
## [1,]    0    0  255
## purple-ish
pal(0.5)
##       [,1] [,2]  [,3]
## [1,] 127.5    0 127.5
pal(seq(0, 1, len = 10))
##            [,1] [,2]      [,3]
##  [1,] 255.00000    0   0.00000
##  [2,] 226.66667    0  28.33333
##  [3,] 198.33333    0  56.66667
##  [4,] 170.00000    0  85.00000
##  [5,] 141.66667    0 113.33333
##  [6,] 113.33333    0 141.66667
##  [7,]  85.00000    0 170.00000
##  [8,]  56.66667    0 198.33333
##  [9,]  28.33333    0 226.66667
## [10,]   0.00000    0 255.00000

colorRampPalette()

pal <- colorRampPalette(c("red", "yellow"))

## Just return red and yellow
pal(2)
## [1] "#FF0000" "#FFFF00"
## Return 10 colors in between red and yellow
pal(10)
##  [1] "#FF0000" "#FF1C00" "#FF3800" "#FF5500" "#FF7100" "#FF8D00" "#FFAA00"
##  [8] "#FFC600" "#FFE200" "#FFFF00"
rgb(0, 0, 234, maxColorValue = 255)
## [1] "#0000EA"

RColorBrewer Package

The RColorBrewer packge offers three types of palettes:

library(RColorBrewer)
display.brewer.all()

Using the RColorBrewer palettes

cols <- brewer.pal(3, "BuGn")
cols
## [1] "#E5F5F9" "#99D8C9" "#2CA25F"
image(volcano, col = pal(20))

The smoothScatter() function

set.seed(1)
x <- rnorm(10000)
y <- rnorm(10000)
smoothScatter(x, y)

Adding transparency

rgb(1, 0, 0, 0.1)
## [1] "#FF00001A"
set.seed(2)
x <- rnorm(2000)
y <- rnorm(2000)
plot(x, y, pch = 19)

plot(x, y, pch = 19, col = rgb(0, 0, 0, 0.15))

Summary

Careful use of colors in plots, images, maps, and other data graphics can make it easier for the reader to get what you’re trying to say (why make it harder?).