mat*_*teo 4 r smoothing lattice
我想使用晶格来创建多面板散点图,并使用分组因子在每个面板中添加平滑线,这里是一个虚拟数据帧
x <- rep(1:10, 4)
a <- as.factor(rep(1:4, 10))
b <- as.factor(sort(rep(1:2, 20)))
y <- rep(NA, 80)
df <- data.frame(x, y, a, b)
df$y[df$b=="1"] <- df$x[df$b=="1"]+df$x[df$b=="1"]^0.5
df$y[df$b=="2"] <- df$x[df$b=="2"]+df$x[df$b=="2"]^1
df$y[df$b=="3"] <- df$x[df$b=="3"]+df$x[df$b=="3"]^2
for(i in 1:80) df$y[i] <- df$y[i]+rnorm(1, 0, 10)
Run Code Online (Sandbox Code Playgroud)
我试过这个:
library(lattice)
xyplot(y ~ x|a, data = df, groups = b, type = "b",
panel = function(x, y,...){
panel.smooth(x, y, ...)
panel.xyplot(x, y, ...)
})
Run Code Online (Sandbox Code Playgroud)
但似乎没有用,我不明白为什么,肯定是我缺少的东西.但是,我还有另外一个问题,就是我需要更改一些平滑参数(span和degree).我找到了一种方法,通过Chi in Cross Validated在线进行(引用其他用户以这种方式工作是否正确?),即:
my.panel.loess <- function(x, y, span = 2/3, degree = 0.5, ...) {
loess.fit <- loess.smooth(x, y, span = span, dgree = degree )
panel.lines(loess.fit$x, loess.fit$y, ...)
panel.xyplot(x, y, ...)}
xyplot(y ~ x|a, data = df, groups = b, type = "b",
panel=function(...)
panel.superpose(panel.groups=my.panel.loess, ...))
Run Code Online (Sandbox Code Playgroud)
但我不能让它为黄土更平滑地绘制一条线并指向原始数据点.我试图在自定义函数中添加参数类型,但格不喜欢多参数.有什么建议吗?
或者没有latticeExtra,只需:
xyplot(y~ x|a, data = df, groups = b, type = c("p", "smooth"))
Run Code Online (Sandbox Code Playgroud)