关于stat_smooth的r:smooth.Pspline包装器(在ggplot2中)

smooth.Pspline wrapper for stat_smooth (in ggplot2)

很抱歉,这个问题不重要,但是我试图弄清楚如何在R中绘制某种类型的自然三次样条(NCS),而这完全使我望而却步。

在上一个问题中,我学习了如何在ggplot中绘制由ns()命令生成的NCS,但是我对如何在pspline包中绘制一个稍有不同的NCS生成的smooth.Pspline命令感兴趣。据我所知,这是唯一为给定的数据集按CV自动选择适当的平滑代价的软件包。

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

1
2
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)

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

非常感谢!


您只需要检查predict.smooth.Pspline如何返回预测值。

stat_smooth的内部工作方式中,调用predictdf创建平滑线。 predictdfggplot2的内部(未导出)功能(在此定义),它是标准的S3方法。

sm.spline返回类smooth.Pspline的对象,因此,要使stat_smooth起作用,您需要为类smooth.Psplinepredictdf创建方法。

因此,以下内容将起作用。

1
2
3
4
5
6
7
8
9
10
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))
}

一个示例(使用mgcv::gam作为比较拟合的pspline)。 mgcv很棒,并且在拟合方法和平滑样条曲线选择方面提供了极大的灵活性(尽管不是CV,只有GCV / UBRE / REML / ML)

1
2
3
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'))

enter