How to properly display matrix as images

How to properly display matrices as image?

R base has at least two methods for displaying matrices or images, either using image, or imageRaster. Each method has its advantages, disadvantages and pitfalls.

Suppose we have calculated the following matrix that we want to display as an image:

M <- matrix (c(2, 2, 0, 1, 0, 0), ncol=3, byrow=TRUE)
i <- 1:2
j <- 1:3

     [,1] [,2] [,3]
[1,]    2    2    0
[2,]    1    0    0 

One of the method is using the image function:

image (x=i, y=j, z=M, asp = 1, useRaster = TRUE)
ij <- expand.grid(i=i, j=j)
text (x=ij$i, y=ij$j, paste ("M[", ij$i, ",", ij$j, "]=", M[cbind (ij$i, ij$j)], sep="")) 

We refer to the matrix element M[i,j]. When using image, i is the x-axis, j is the y-axis. With this solution, the matrix as written is rotated 90° anticlockwise on the screen.

Note the usage of asp=1 option in the call to image. This way, matrix element are squares. useRaster=TRUE is used to speed up the display of large matrices (yet, not necessary in this example…).

If you want your matrix displayed as a raster image (first coordinates on top-left), you can try this:

image (x=j, y=i, z=t (M), 
       ylim = rev (range (i) + c (-1, 1) * (max (i) - min (i)) / length (i)),
       asp = 1, useRaster = TRUE)
ij <- expand.grid(i=i, j=j)
text (x=ij$j, y=ij$i, paste ("(", ij$i, ",", ij$j, ")", sep=""))

Note here the matrix transposition and the reversal of y axis, in order to preserve the orientation.