2016-02-29 27 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

有沒有更好的辦法? –