在下面的示例中,我需要显示按分组变量class
分层的每个面板中每个单元格的值:
library("lattice")
x <- seq(pi/4, 5*pi, length.out=5)
y <- seq(pi/4, 5*pi, length.out=5)
r1 <- as.vector(sqrt(outer(x^2, y^2, "+")))
r2 <- as.vector(sqrt(outer(x^2, y^2, "/")))
grid1 <- grid2 <- expand.grid(x=x, y=y)
grid1$z <- cos(r1^2)*exp(-r1/(pi^3))
grid2$z <- cos(r2^2)*exp(-r2/(pi^3))
grid <- rbind(grid1, grid2)
grid$class <- c(rep("addition",length(x)^2), rep("division", length(x)^2))
p <- levelplot(z~x*y | factor(class), grid,
panel=function(...) {
arg <- list(...)
panel.levelplot(...)
panel.text(arg$x, arg$y, round(arg$z,1))})
print(p)
答案 0 :(得分:2)
稍微落后于幕后,格使用名为subscripts
的参数来对数据进行子集化,以便在不同的面板中显示。通常,它是在没有你需要知道的情况下这样做的,但这不是那种情况之一。
查看panel.levelplot
的源代码会发现它自己处理subscripts
。 args(panel.levelplot)
表明它是函数的形式参数之一,函数的主体显示它是如何使用它们的。
panel.text()
(实际上只是lattice:::ltext.default()
的包装器)不知道subscripts
或对panel.text(x,y,z)
做任何事情。在致电x
的过程中,看到的y
,z
和grid
是data.frame subscripts
的完整列,为什么你看到了你所做的过度绘图。
要绘制属于当前面板一部分的值的文本,您需要明确使用myPanel <- function(x, y, z, ..., subscripts=subscripts) {
panel.levelplot(x=x, y=y, z=z, ..., subscripts=subscripts)
panel.text(x = x[subscripts],
y = y[subscripts],
labels = round(z[subscripts], 1))
}
p <- levelplot(z~x*y | factor(class), grid, panel = myPanel)
print(p)
参数,如下所示:
*alloc()