Colors with R: 100 Shades of Blue

Figure 1. A 10 by 10 matrix of blue.

For a list of colour names as character strings in R (R Development Core Team, 2011), just enter “colors( )” into the R console. But what if you want to get quantitative? You can also reference colours with character strings composed of the “#” sign and a hexadecimal number. For example, the string “#0000FF” indicates a bright blue. Figure 1 was produced with the R script given below. WordPress seems to convert straight quotation marks into left and right quotation marks that can’t be read by R; thus, the script below contains some obscure syntax for the sake of avoiding quotation marks. (The majority of the script simply converts decimal numbers to hexadecimal character strings. You might be able to find an easier way to do this … .) See if you can alter the script to make shades of your favorite colour!

R Script (short version)


R Script (long version)

as.hex.string <- function(n){
hex.digits <- character(16);
for (i in 1:9) hex.digits[i] <- as.character(i);
for (i in 10:15) hex.digits[i] <- LETTERS[i-9];
hex.digits[16] <- as.character(0);
if (n<16) H <- paste(as.character(0),hex.digits[n],sep=character(1));
if (n==0) H <-paste(as.character(0), as.character(0), sep=character(1));
if (n>=16) {
H1 <- hex.digits[n%/%16];
n <- n-(n%/%16)*16;
H2 <- hex.digits[n];
if (n==0) H2 <- as.character(0);
H <- paste(H1,H2,sep=character(1));

as.colour.string <- function(R,G,B){
r <- as.hex.string(R);
g <- as.hex.string(G);
b <- as.hex.string(B);

X <- seq(0,255,1);
BLUE <- numeric(256);
for (i in 1:256){BLUE[i] <- as.colour.string(0,0,X[i]);}
M <- matrix(0,10,10);
for (i in 1:10) for (j in 1:10) M[i,j] <- (sample(256,1)-1);


R Development Core Team, 2011. R: A language and environment for statistical       computing. R Foundation for Statistical Computing, Vienna, Austria.


One thought on “Colors with R: 100 Shades of Blue

  1. For a less fun, less do-it-yourself approach you can get the same result with one line of code:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s