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

时间:2013-10-10 00:08:57

标签: r plot ggplot2

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

previous question中,我学会了如何绘制ggplot中ns()命令生成的NCS,但我对如何绘制略有不同的NCS感兴趣,生成了{{{{{{ 3}}包。据我所知,这是唯一一个能够通过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)

我想用smooth.Pspline的功能替换“lm”公式。我做了一点谷歌搜索,发现了一个pspline到非常相似的B样条函数smooth.spline,由Hadley编写。但是我无法使其适应光滑.Pspline非常完美。有没有人有这方面的经验?

非常感谢!

1 个答案:

答案 0 :(得分:8)

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

stat_smooth的内部工作中,调用predictdf来创建平滑线。 predictdfggplot2的内部(非导出)函数(定义为here),它是标准的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))
}

一个例子(使用mgcv::gam作为比较拟合pspline)。 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'))

enter image description here