R:由分组变量

问题描述:

在下面的例子分层在levelplot显示值,我需要在每个由所述分组变量class分层面板的显示每个细胞的值:R:由分组变量

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

略幕后,晶格使用称为subscripts到子集的数据在不同的面板显示的参数。通常情况下,它并不需要知道它,但这不是其中的一种情况。

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

panel.text()(真的只是lattice:::ltext.default()的包装),另一方面,不知道或做任何事情subscripts。从致电panel.text(x,y,z)x,yz,看到的是data.frame grid的完整列,这就是为什么您看到您所做的重叠绘图。

,以便为在当前面板的一部分值绘制文本,你需要明确使用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) 

enter image description here

+0

谢谢你的非常详细回答。我已经通过使用'panel.number()'找出了解决方法,但是您的解决方案更加优雅。 – aenima

+0

非常欢迎。这是一个很好的问题,最终给我一个更好的处理方法,而且不需要混淆下标。 –