2013-10-10 48 views
3

對不起,如果這個問題是微不足道的,但我想弄清楚如何在R中繪製某種類型的自然立方樣條(NCS),它完全躲過了我。stat.smooth(在ggplot2中)smooth.Pline包裝

previous question我學會了如何在ggplot中繪製ns()命令生成的NCS,但是我感興趣的是如何在pspline包中生成略有不同的NCS生成smooth.Pspline命令。據我所知,這是唯一一個可以根據給定數據集自動選擇適當CV平滑懲罰的軟件包。

理想情況下,我將能夠提供smooth.Pline作爲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」公式。我做了一些搜索,發現了Hadley編寫的非常相似的B樣條函數smooth.spline的solution。但我無法完美地適應這種平滑。有人對此有經驗嗎?

非常感謝!

回答

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)) 
} 

一個例子(具有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')) 

enter image description here

+1

你能解釋一下函數或類調度原則,導致'predictdf.smooth.Pspline'被稱爲?哈德利寫這篇文章的時候我並沒有明白,但我也沒有看到這方面的聯繫。我發現stat_smooth應該返回與您爲該函數的參數設置相同的值,但是什麼決定了它如何命名或被調用? –

+0

@Dwin - 我已經編輯了答案。 – mnel

+0

你們在這裏很棒。謝謝你的偉大答案。 – gogurt