[英]smooth.Pspline wrapper for stat_smooth (in 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)
我想用smooth.Pspline的功能替換“lm”公式。 我做了一些谷歌搜索,並找到了一個非常相似的B樣條函數smooth.spline的解決方案 ,由Hadley編寫。 但是我無法使其適應光滑.Pspline非常完美。 有任何人對此有經驗嗎?
非常感謝!
您只需要檢查predict.smooth.Pspline
如何返回預測值。
在stat_smooth
的內部工作中, predictdf
來創建平滑線。 predictdf
是內部(非導出)函數ggplot2
(它被定義在這里 )它是一個標准方法,S3。
sm.spline
返回類smooth.Pspline
的對象,因此stat_smooth
工作,您需要為類smooth.Pspline
創建predictdf
方法。
因此,以下將起作用。
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
作為比較安裝了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'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.