11

I have the following 4x4 number matrix containing the numbers 0-4:

0  1  0  3
3  2  1  4
4  1  0  2
3  3  0  1

I would like to understand how to convert number matrices into a color matrices using chosen colors and specific square dimensions (length x width) using R. To be clear, I'm defining color matrix as a figure using colored squares to represent specific values in a matrix orientation. An example 4x4 from another program follows:

enter image description here

I would have to assign color codes to the numbers, for example:

0 = FFFFFF
1 = 99FF66
2 = 66FF33
3 = 33CC00
4 = 009900

But I don't know where to begin putting this together. I imagine I would also have to specify dimensions for color squares as well.

My goal is to be able to import a data frame into R with up to 10 numerical values and create these color charts for matrices as large as 20x20.

Cameron
  • 149
  • 1
  • 10

1 Answers1

11

Here's what I would do:

d<-read.table(text="
0  1  0  3
3  2  1  4
4  1  0  2
3  3  0  1")

cols <- c(
'0' = "#FFFFFF",
'1' = "#99FF66",
'2' = "#66FF33",
'3' = "#33CC00",
'4' = "#009900"
)
# the names aren't necessary here.

image(1:nrow(d), 1:ncol(d), as.matrix(d), col=cols)

enter image description here

If you'd prefer for the orientation to be different, you can rotate the matrix:

image(1:nrow(d), 1:ncol(d), t(apply(d, 2, rev)), col=cols)

To get rid of all the text and borders, you might try:

image(1:nrow(d), 1:ncol(d), as.matrix(d), col=cols, 
  xaxt="n", yaxt="n", bty="n", xlab="", ylab="")
Community
  • 1
  • 1
Jota
  • 17,281
  • 7
  • 63
  • 93
  • I used the following code to generate a color matrix without the text and borders: `image(1:nrow(d), 1:ncol(d), t(apply(d, 2, rev)), col=cols, xaxt='n', yaxt='n', ann=FALSE, bty='n')` It worked beautifully! The only issue I'm having now is that the squares came out a little rectangular. Is there a way to lock the aspect ratio such that the color squares remain perfectly square? – Cameron Jun 04 '15 at 04:49
  • 3
    @Cameron You could try adding `asp=1` as one of the arguments to `image`: `image(1:nrow(d), 1:ncol(d), t(apply(d, 2, rev)), col=cols, xaxt='n', yaxt='n', ann=FALSE, bty='n', asp = 1)`. – Jota Jun 04 '15 at 04:53
  • 1
    Or open a new window with square dimensions (e.g. `windows(width=6,height=6)` ) and then set the margins as the same on every side `par(mar=c(1,1,1,1))` – thelatemail Jun 04 '15 at 04:57