R:由分组变量分层的水平图中的显示值

时间:2016-03-02 19:00:33

标签: r graphics lattice

在下面的示例中,我需要显示按分组变量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)

然而,单元格值彼此叠加,因为面板选项不能区分两组。如何在每个组中正确显示值? enter image description here

1 个答案:

答案 0 :(得分:2)

稍微落后于幕后,使用名为subscripts的参数来对数据进行子集化,以便在不同的面板中显示。通常,它是在没有你需要知道的情况下这样做的,但这不是那种情况之一。

查看panel.levelplot的源代码会发现它自己处理subscriptsargs(panel.levelplot)表明它是函数的形式参数之一,函数的主体显示它是如何使用它们的。

另一方面,

panel.text()(实际上只是lattice:::ltext.default()的包装器)不知道subscripts或对panel.text(x,y,z)做任何事情。在致电x的过程中,看到的yzgrid是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()

enter image description here