5

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.

Community
  • 1
  • 1
forochelian
  • 171
  • 2
  • 8

3 Answers3

12

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

Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
  • Old answer I know but how might I go about excluding NA values from displaying a text label with this example panel function? – Rich Wawrzonek Oct 03 '18 at 23:22
  • 1
    @RichWawrzonek Inside of `myPanel`, I'd explicitly convert `z` to a character vector and then change all of the `NA`s to empty strings. Something like this for the body of `myPanel`: `{panel.levelplot(x,y,z,...); zz <- as.character(round(z,1)); zz[is.na(zz)] <- ""; panel.text(x, y, zz)}` – Josh O'Brien Oct 04 '18 at 01:40
4
mat <- read.csv("J_H2S1T6_PassTraffic.csv", header=F)

y        <- as.numeric(mat[1,-1])
mat      <- mat[-1,-1]
n        <- dim(mat)[1]

Here a modification, I generate a new scale

x <- seq(min(y), max(y), length.out=n)
grid     <- expand.grid(x=x, y=x)
mat      <- as.matrix(mat)
dim(mat) <- c(n*n,1)
grid$z   <- mat

Here the modification. I change the dimension of the matrix to a vector to put it in the grid .

mat <- as.matrix(mat)
dim(mat) <- c(n*n,1)
grid$z <- mat

p <- levelplot(z~x*y, grid, 
           panel=function(...) {
             arg <- list(...)
             panel.levelplot(...)
             panel.text(arg$x, arg$y,arg$z)},
           scales = list(y = list(at=y,labels=y),
                         x = list(at=y,labels=y)))

print(p)

enter image description here

Julius Vainora
  • 47,421
  • 9
  • 90
  • 102
agstudy
  • 119,832
  • 17
  • 199
  • 261
2

Another option is to use layer() from latticeExtra. It allows you to overlay one plot on top of another, using the + operator familiar to ggplot2 enthusiasts:

library(latticeExtra)

## Applied to the example data in my other answer, this will produce
## an identical plot
levelplot(Z ~ X*Y, data = grid) +
layer(panel.text(X, Y, round(Z, 1)), data = grid)
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455