rgb

rgb(red, green, blue, alpha)
Specify the amount of red, green, and blue for a color in a plot, and add transparency using the alpha level.
  • red – A number (or vector of numbers) between 0 and 1, where higher numbers mean more red.
  • green – A number (or vector of numbers) between 0 and 1, where higher numbers mean more green.
  • blue – A number (or vector of numbers) between 0 and 1, where higher numbers mean more blue.
  • alpha – A number (or vector of numbers) between 0 and 1, where 0 is fully transparent and 1 is opaque.

Example. Data for a simple scatterplot is constructed. A third variable, z, was also constructed to represent some third variable that was incorporated into the coloring of the plot. The first plot uses a color transition from red (smaller z) to blue (larger z), the second uses only transparency, and the third plot varies color and keeps a consistent transparency. Note that transparency will not always work on Windows machines by default, but saving the file via CairoPNG (or similar functions, like CairoPDF) is analogous to png (or pdf) but uses a plotting device that records alpha levels.
> # If using Windows, may need to use Cairo
> # package to utilize transparency
> # 
> # library(Cairo)
> 
> set.seed(5)
> x  <- runif(100)
> y  <- 4*x + rnorm(100)
> z  <- 2*x + 0.3*y + rnorm(100, sd=0.5)
> c1 <- (z - min(z)) / (max(z) - min(z))
> c2 <- (z - min(z) + 2) / (max(z) - min(z) + 2)
> 
> col1 <- rgb(1-c1, 0.5*c1, c1)
> col1[1:5]
[1] "#764589" "#4060BF" "#2E69D1" "#8B3A74" "#C41D3B"
> 
> col2 <- rgb(0, 0, 0, c2)
> col2[1:5]
[1] "#000000AB" "#000000D1" "#000000DE" "#0000009C"
[5] "#00000072"
> 
> col3 <- rgb(1-c1, 0.5*c1, c1, 0.7)
> col3[1:5]
[1] "#76458999" "#4060BF99" "#2E69D199" "#8B3A7499"
[5] "#C41D3B99"
> 
> # CairoPNG("rgb1.png")
> png("rgb1.png")
> plot(x, y, col=col1, pch=19, cex=4)
> dev.off()
null device 
          1 
> 
> # CairoPNG("rgb2.png")
> png("rgb2.png")
> plot(x, y, col=col2, pch=19, cex=4)
> dev.off()
null device 
          1 
> 
> # CairoPNG("rgb3.png")
> png("rgb3.png")
> plot(x, y, col=col3, pch=19, cex=4)
> dev.off()
null device 
          1 
The set.seed makes the code reproducible, and the png function was used to save each of the plots to a file.

Leave a Reply