2016-02-29 87 views
3

我想打印具有分组点和直线的lattice::xyplot,但对于各组中的许多个人x值,我有多个y值。我想要一个分段的行打印,以便每个x值,它通过每个组中的相关y值的平均值。格点 - 通过y值的平均值添加直线

下面是一个例子:

使用此数据:

set.seed(1) 
d <- data.frame(x=sample(6, 20, replace=TRUE), y=rnorm(20), g=factor(sample(2, 20, replace=TRUE))) 
# Shift one group 
d$y[d$g==2] = d$y[d$g==2] + 5 

我移动一个组,这样的线条在视觉上更加吸引人。

散点图看起来是这样的:

xyplot(y ~ x, data=d, groups=g) 

enter image description here

只是增加线是一个真正的混乱:

xyplot(y ~ x, data=d, groups=g, type=c('p','l')) 

enter image description here

这有点如果好一点x值,但stil L不就是我想要的:

xyplot(y ~ x, data=d[order(d$x),], groups=g, type=c('p','l')) 

enter image description here

回答

4

我会使用panel.superpose,然后在组面板功能中进行聚合。例如

xyplot(y ~ x, data=d, groups=g, panel=function(...) { 
    panel.xyplot(...); 
    panel.superpose(..., panel.groups=function(x,y,col.line,...) { 
     dd<-aggregate(y~x,data.frame(x,y),mean) 
     panel.xyplot(x=dd$x, y=dd$y, col=col.line, type="l") 
    }) 
}) 

这导致

enter image description here

+0

这就是我要找的。 –

0
xyplot(y ~ x, data=d, groups=g, 
     panel = function(x, y, subscripts, groups, ...) {  
     grp <- as.numeric(groups[subscripts]) 
     col <- trellis.par.get()$superpose.symbol$col 
     panel.xyplot(x, y, subscripts=subscripts, groups=groups, ...) 
     for (g in unique(grp)) { 
      sel <- g == grp 
      m <- aggregate(list(y=y[sel]), list(x=x[sel]), FUN=mean) 
      panel.lines(m$x, m$y, col=col[g]) 
     } 
     } 
) 

enter image description here

所以这是怎么回事呢? subscripts是每个面板的下标列表。在我的小例子中没有调节,所以它是1:20。同样,groups是该面板的组列表。再次,有一个面板,所以这是d$g

grp然后是其因子中每个组的索引。

col是颜色集合,在panel.lines函数中索引以选择与点相同的颜色。

对于每个组,将为该组中的每个x值计算平均值,并将该平均值传递给坐标的panel.lines

+0

有没有更好的办法? –