1

I am aware of this thread - How to show matrix values on Levelplot

and this thread - Showing data values on levelplot in R

that ask similar questions. But I don't quite see how I can adapt the code to what I am trying.

I have a matrix (M1) that I can make a levelplot from. What I would like to do is add the respective value from each 'cell' in M1 to the corresponding 'cell' in the levelplot. I have been trying with panel.levelplot but I just can't figure out how to define the variables x,y,z.

A follow up question would be... if I can create a levelplot from matrix M1, but I want to add the values from another matrix (M2) of exactly the same size. How can this be done?

Example data:

#Matrix1
M1 <- matrix(0, nrow=5, ncol=5)
M1[upper.tri(M1, diag = FALSE)]<-1
M1

#Matrix2
M2<-matrix(sample.int(25, replace = TRUE), nrow = 5, ncol = 5)
M2

#This makes a levelplot but how to add the values from a) Matrix M1, b) Matrix M2
levelplot(M1[1:ncol(M1),ncol(M1):1])
Community
  • 1
  • 1
jalapic
  • 13,792
  • 8
  • 57
  • 87

1 Answers1

3

Following the first question , for example, you just slightly modify it to include M2 values.

myPanel <- function(x, y, z, ...) {
  panel.levelplot(x,y,z,...)
  panel.text(x, y,  M2[cbind(x,y)]) ## use handy matrix indexing
}

Then you get your result :

levelplot(M1,panel=myPanel)

enter image description here

To orient whole thing so that M1[1,1] is in the upper left corner, as it would be if you simply printed M1, do it this way (see comment from Bryan):

M3 <- t(M1[nrow(M1):1,])
levelplot(M3, panel = myPanel)
Bryan Hanson
  • 6,055
  • 4
  • 41
  • 78
agstudy
  • 119,832
  • 17
  • 199
  • 261
  • Thanks - I think this is half way there. The only issue is in that my running of this the overlaid numbers do not correspond to the correct cells. If we do M1 which is a defined matrix - (M2 is random numbers and will look different for different users), then the plot as colored above is plotting row (x-axis) vs column (y-axis). The matrix as looked at visually as a table of numbers is row on the y and columns on the x. (i.e. the upper triangle has 1's and the lower triangle the 0s). Is there a way to switch the levelplot such that it looks like the original matrix in configuration? – jalapic Apr 03 '14 at 14:15
  • I have tried using the command as.table=TRUE from the ?xyplot help section, but this doesn't seem to do anything ??? – jalapic Apr 03 '14 at 14:29
  • 1
    The missing piece you need is to do `M2 <- t(M1[nrow(M1):1,])` then call your function using `M2`. The reason for this is that `levelplot`, `contour` and `image` functions were all built so that `M[1,1]` is in the lower left corner. This orientation has been perpetuated for compatibility. – Bryan Hanson Dec 17 '14 at 02:45