# Colors with R: 100 Shades 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)

image(matrix(runif(100),10,10),col=rgb(0,0,seq(0.01,1,0.01)),axes=FALSE);

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 <- 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));
}
H;
}

as.colour.string <- function(R,G,B){
r <- as.hex.string(R);
g <- as.hex.string(G);
b <- as.hex.string(B);
paste(rawToChar(as.raw(35)),r,g,b,sep=character(1));
}

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);
image(M,col=BLUE,axes=FALSE)

References

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

## 1 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:

image(matrix(runif(100),10,10),col=rgb(0,0,seq(0.01,0.99,0.01)),axes=FALSE);