R lattice包中的panel函数参数传输的一个问题

来源:互联网 发布:人知从太守游而乐的而 编辑:程序博客网 时间:2024/04/30 07:20

R语言lattice包可以自己定制panel函数。当使用高级函数(例如xyplot,levelplot)绘图时,会调用相应的panel函数来给每个panel(面板)绘图。
最近发现不同的函数传将参数输给面板函数的方式有所不同。

首先来看看xyplot。

library(lattice)# 这里定义一个简单的panel函数,打印传输进来的变量myPanel <- function(x, y, subscripts, ...) {    panel.xyplot(x, y, ...)    cat('调用myPanel:\n')    cat('x: ', x, '\n')    cat('y: ', y, '\n')    cat('subscripts: ', subscripts, '\n\n')}data <- data.frame(x = 1:24, y = 1:24, g = factor(rep(1:3, 8)))xyplot(x ~ y | g, data = data, aspect=1, layout=c(3, 1),    panel=myPanel)

结果:

## 调用myPanel:## x:  1 4 7 10 13 16 19 22 ## y:  1 4 7 10 13 16 19 22 ## subscripts:  1 4 7 10 13 16 19 22 ## ## 调用myPanel:## x:  2 5 8 11 14 17 20 23 ## y:  2 5 8 11 14 17 20 23 ## subscripts:  2 5 8 11 14 17 20 23 ## ## 调用myPanel:## x:  3 6 9 12 15 18 21 24 ## y:  3 6 9 12 15 18 21 24 ## subscripts:  3 6 9 12 15 18 21 24

可见,当xyplot每次调用myPanel时,将原始data数据框中24行数据拆成了3份,每次传输一份给myPanel函数。其中subscripts是每份数据在原始数据中对应的编号。
下面来看看levelplot。我们写个类似的例子。

myPanel <- function(x, y, z, subscripts, ...) {    panel.levelplot(x, y, z, subscripts, ...)    cat('调用myPanel:\n')    cat('x: ', x, '\n')    cat('y: ', y, '\n')    cat('z: ', z, '\n')    cat('subscripts: ', subscripts, '\n\n')}data <- data.frame(x = 1:24, y = 1:24, z = 1 : 24,                   g = factor(rep(1:3, 8)))levelplot(z~x*y | g, data = data, aspect=1, layout=c(3, 1),    panel=myPanel)

结果:

## 调用myPanel:## x:  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ## y:  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ## z:  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ## subscripts:  1 4 7 10 13 16 19 22 ## ## 调用myPanel:## x:  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ## y:  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ## z:  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ## subscripts:  2 5 8 11 14 17 20 23 ## ## 调用myPanel:## x:  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ## y:  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ## z:  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ## subscripts:  3 6 9 12 15 18 21 24

我们发现,levelplot每次传输给myPanel中的x,y,z都是原始data中所有的数据,只是subscripts中保存了每次的分组信息。

如果自己写panel函数,这些行为需要注意一下。

此外需要注意,默认的panel函数中,panel.xyplot函数没有参数subscripts,而panel.levelplot有这个参数。这与上面分析的问题是一致的。

0 0
原创粉丝点击