How to show matrix values on Levelplot

forochelian picture forochelian · Dec 15, 2012 · Viewed 9k times · Source

I have a matrix data here, and I visualized it with levelplot. The Plot is placed below. But I just couldn't put the values into the plot, I mean I read this question, but still couldn't figure it out.

How can I do that ? Thanks.

Answer

Josh O'Brien picture Josh O'Brien · Dec 15, 2012

The problem with the code in the answer you linked to is that it only works when the objects in the levelplot's formula are named x, y, and z.

Here is an example that uses a more standard idiom for processing the arguments passed in to the custom panel function and so becomes more generally applicable:

library("lattice")

## Example data
x <- seq(pi/4, 5*pi, length.out=10)
y <- seq(pi/4, 5*pi, length.out=10)
grid <- expand.grid(X=x, Y=y)
grid$Z <- runif(100, -1, 1)

## Write a panel function (after examining 'args(panel.levelplot) to see what
## will be being passed on to the panel function by levelplot())
myPanel <- function(x, y, z, ...) {
    panel.levelplot(x,y,z,...)
    panel.text(x, y, round(z,1))
}

## Try it out
levelplot(Z ~ X*Y, grid, panel = myPanel)

enter image description here