格点 - 通过y值的平均值添加直线
问题描述:
我想打印具有分组点和直线的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)
只是增加线是一个真正的混乱:
xyplot(y ~ x, data=d, groups=g, type=c('p','l'))
这有点如果好一点x
值,但stil L不就是我想要的:
xyplot(y ~ x, data=d[order(d$x),], groups=g, type=c('p','l'))
答
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])
}
}
)
所以这是怎么回事呢? subscripts
是每个面板的下标列表。在我的小例子中没有调节,所以它是1:20
。同样,groups
是该面板的组列表。再次,有一个面板,所以这是d$g
。
grp
然后是其因子中每个组的索引。
col
是颜色集合,在panel.lines
函数中索引以选择与点相同的颜色。
对于每个组,将为该组中的每个x
值计算平均值,并将该平均值传递给坐标的panel.lines
。
+0
有没有更好的办法? –
这就是我要找的。 –