R 格中带分组因子的多面板光滑
我想使用lattice创建多面板散点图,并使用分组因子通过每个面板添加平滑线,这是一个虚拟数据帧R 格中带分组因子的多面板光滑,r,lattice,smoothing,R,Lattice,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
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)
但似乎不起作用,我不明白为什么,肯定是我错过了什么。
但是,我还有一个问题,那就是,我需要更改一些平滑参数(跨度和度)。我在交叉验证中找到了一种在线实现的方法(以这种方式引用其他用户的工作是否正确?),即:
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, ...))
my.panel.alluch我经常发现latticeExtra(及其层()
,as.layer()
,以及重载的+
操作符)对您这样的设置有很大帮助:
library(latticeExtra)
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, ...)
}
## A plot with the smoothing lines
a <- xyplot(y ~ x|a, data = df, groups = b, type="l",
panel=function(...) panel.superpose(panel.groups=my.panel.loess,...))
## A plot with the points
b <- xyplot(y ~ x|a, data=df, groups=b)
## Both together
plot(a+b)
库(latticeExtra)
my.panel.Leash或不带latticeExtra,只需:
xyplot(y~ x|a, data = df, groups = b, type = c("p", "smooth"))
谢谢Josh,我需要更深入地探索latticeExtra。
xyplot(y~ x|a, data = df, groups = b, type = c("p", "smooth"))