Tnunes
Tnunes

Reputation: 87

R: Predefined background colors for a matrix

On a report I would like to represent a state change matrix between dates. Lets say I have a matrix like this:

B = data.frame(c(0, 0, 0, 5, 0, 0,5,0,0,5,0,0,5,0,0,0), nrow=4, ncol=4) 
dimnames(B)<-list(c("A","B","C","D"),c("D","C","B","A"))

B would be something like this:

  D C B A
A 0 0 0 5
B 0 0 5 0
C 0 5 0 0
D 5 0 0 0

Any change from D->C->B->A would be an improvement and changes from A->B->C->D would be a problem.

I would like to have this represented (will be used in a knitr document) with a neutral background color in the diagonal (the 5's in my matrix) and then green at the right of the diagonal (improvement) and red to the left (problem). Any suggestion how to do this? The numbers should appear anyway and shouldn't change the background colors.

Any further suggestions on alternatives to represent this are welcome.

Upvotes: 2

Views: 275

Answers (1)

J&#246;rg M&#228;der
J&#246;rg M&#228;der

Reputation: 677

New version without a 'hand-made' matrix for the image command

## the input data as vector (as in the question)
## size has to be a square number
values <- c(0, 0, 0, 5, 0, 0,5,0,0,5,0,0,5,0,0,0)

size <- sqrt(length(values))
a <- matrix(0, nrow=size, ncol=size)
a[lower.tri(a)] <- +1
a[upper.tri(a)] <- -1
image(a,col=c('red','transparent','green'),xaxt='n',yaxt='n',xlab='',ylab='')
text(rep(seq(1,0,len=size),len=size*size),rep(seq(0,1,len=size),each=size),values)

Upvotes: 4

Related Questions