2013-02-08 20 views
2

我有這樣的數據,以便在不同的日子(POSIXct格式)給一個主題得分。ggplot多項式擬合與日期作爲解釋變量

head(test) 
     Date Subject score 
1 2012-08-10 Black6  0 
2 2012-08-11 Black6  0 
3 2012-08-12 Black6  0 
4 2012-08-13 Black6  0 
5 2012-08-14 Black6  0 
6 2012-08-15 Black6  0 

擬合黃土曲線很簡單。

ggplot(test,aes(Date,score))+geom_smooth()+geom_point() 

enter image description here 我希望做的是安裝一個3階多項式線。如果我在下面的類型我得到一個錯誤:

ggplot(test,aes(Date,score))+stat_smooth(method = "lm", formula = score ~ poly(Date, 3), size = 1)+geom_point() 
Error in eval(expr, envir, enclos) : object 'score' not found 

我得到同樣的錯誤,如果我指定的日期爲數字stat_smooth內()。有沒有辦法在ggplot中做到這一點?

這裏的數據:

test<-structure(list(Date = structure(c(1344556800, 1344643200, 1344729600, 
1344816000, 1344902400, 1344988800, 1345075200, 1345161600, 1345248000, 
1345334400, 1345420800, 1345507200, 1345593600, 1345680000, 1345766400, 
1345852800, 1345939200, 1346025600, 1346112000, 1346198400, 1346284800, 
1346371200, 1346457600, 1346544000, 1346630400, 1346716800, 1346803200, 
1346889600, 1346976000, 1347062400, 1347148800, 1347235200, 1347321600, 
1347408000, 1347494400, 1347580800, 1347667200, 1347753600, 1347840000, 
1347926400, 1348012800, 1348099200, 1348185600, 1348272000, 1348358400, 
1348444800, 1348531200, 1348617600, 1348704000, 1348790400, 1348876800, 
1348963200, 1349049600, 1349136000, 1349222400, 1349308800, 1349395200 
), class = c("POSIXct", "POSIXt"), tzone = "UTC"), Subject = structure(c(1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "Black6", class = "factor"), 
score = c(0, 0, 0, 0, 0, 0, 0, 0.25, 0.25, 0.25, 0.25, 0.25, 
0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 1, 2, 2, 2, 2, 
2, 2, 2, 2, 2, 2, 2, 2, 2, 1.5, 1.5, 1.25, 1.25, 1.25, 1, 
1, 1, 1, 1, 1, 1, 1, 1.5, 1.5, 1.25, 1, 1, 1, 0.5, 0.5, 0.5, 
0.25, 0.25)), .Names = c("Date", "Subject", "score"), row.names = c(NA, 
57L), class = "data.frame") 

回答

4

stat_smooth的公式參數必須在美學yx,不映射到那些美學原始變量的術語來指定。

ggplot(test,aes(Date,score)) + 
    stat_smooth(method = "lm", formula = y ~ poly(x, 3), size = 1) + 
    geom_point() 

enter image description here

+0

大非常感謝! – iantist 2013-02-08 20:19:40

3

即使問題是關於ggplot2,我給他使用latticelatticeExtra包類似的解決方案。

library(lattice) 
    library(latticeExtra) 
    xyplot(score ~ Date, test,par.settings = ggplot2like()) + 
      layer(panel.smoother(y ~ poly(x, 3), method = "lm"), style = 2) 

enter image description here

+0

(+1)並恭喜10K! :) – Arun 2013-02-12 08:41:47

+0

@阿倫謝謝!你會成爲下一個10k-R的傢伙:) – agstudy 2013-02-12 12:59:38

+0

哈哈謝謝! :) – Arun 2013-02-12 13:11:11