用于stat_smooth的smooth.Pspline包装器(在ggplot2中)

gog*_*urt 4 plot r ggplot2

对不起,如果这个问题很简单,但是我想弄清楚如何在R中绘制某种类型的自然三次样条(NCS)并且它完全没有我.

之前的一个问题中,我学会了如何在ggplot中绘制由ns()命令生成的NCS,但我对如何在pspline包中生成稍微不同的NCS生成smooth.Pspline命令感兴趣.据我所知,这是唯一一个自动为CV给定数据集选择适当平滑罚分的包.

理想情况下,我可以提供smooth.Pspline作为ggplot2中stat_smooth图层的方法.我目前的代码如下:

plot <- ggplot(data_plot, aes(x=age, y=wOBA, color=playerID, group=playerID))
plot <- plot + stat_smooth(method = lm, formula = y~ns(x,4),se=FALSE)
Run Code Online (Sandbox Code Playgroud)

我想用smooth.Pspline的功能替换"lm"公式.我做了一些谷歌搜索,并找到了一个非常相似的B样条函数smooth.spline 的解决方案,由Hadley编写.但是我无法使其适应光滑.Pspline非常完美.有任何人对此有经验吗?

非常感谢!

mne*_*nel 8

您只需检查predict.smooth.Pspline返回预测值的方式.

在内部运作中stat_smooth,predictdf被称为创建平滑线.predictdf是内部(非导出)函数ggplot2(它被定义在这里)它是一个标准方法,S3.

sm.spline返回一个类的对象smooth.Pspline,因此为了stat_smooth工作,你需要predictdf为类创建方法smooth.Pspline.

因此,以下将起作用.

smP <- function(formula,data,...){
  M <- model.frame(formula, data)
  sm.spline(x =M[,2],y =M[,1])

}
# an s3 method for predictdf (called within stat_smooth)
predictdf.smooth.Pspline <- function(model, xseq, se, level) {
  pred <- predict(model, xseq)
  data.frame(x = xseq, y = c(pred))
}
Run Code Online (Sandbox Code Playgroud)

一个例子(使用pspline mgcv::gam作为比较).mgcv非常棒,并且在拟合方法和平滑样条选择方面具有很大的灵活性(尽管不是CV,只有GCV/UBRE/REML/ML)

d <- ggplot(mtcars, aes(qsec, wt))
d + geom_point() +  stat_smooth(method = smP, se= FALSE, colour='red', formula = y~x) + 
stat_smooth(method = 'gam', colour = 'blue', formula = y~s(x,bs='ps'))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述