How to show matrix values on Levelplot

拥有回忆 提交于 2019-11-27 20:56:10

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)

agstudy
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)

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!