2010-05-08 71 views
1

我想用這個時間和實際的日期(實際上,1997,1998 ... 2010)進行比較。這些日期是原始格式,ala SAS,自1960年以來的日子(因此as.date轉換)。如果我使用as.date將日期轉換爲變量x,並執行GAM繪圖,則會出現錯誤。它適用於原始日數。但我希望劇情能夠顯示年份(數據不是等距的)。R繪圖 - SGAM繪圖計數與時間的關係 - 如何在x軸上獲取日期?

structure(list(site = c(928L, 928L, 928L, 928L, 928L, 928L, 928L, 
928L, 928L, 928L, 928L, 928L, 928L, 928L, 928L, 928L, 928L, 928L, 
928L, 928L, 928L, 928L, 928L, 928L, 928L, 928L), date = c(13493L, 
13534L, 13566L, 13611L, 13723L, 13752L, 13804L, 13837L, 13927L, 
14028L, 14082L, 14122L, 14150L, 14182L, 14199L, 16198L, 16279L, 
16607L, 16945L, 17545L, 17650L, 17743L, 17868L, 17941L, 18017L, 
18092L), y = c(7L, 7L, 17L, 18L, 17L, 17L, 10L, 3L, 17L, 24L, 
11L, 5L, 5L, 3L, 5L, 14L, 2L, 9L, 9L, 4L, 7L, 6L, 1L, 0L, 5L, 
0L)), .Names = c("site", "date", "y"), class = "data.frame", row.names = c(NA, 
-26L)) 

sgam1 <- gam(sites$y ~ s(sites$date)) 
    sgam <- predict(sgam1, se=TRUE) 
    plot(sites$date,sites$y,xaxt="n", xlab='Time', ylab='Counts') 
    x<-as.Date(sites$date, origin="1960-01-01") 
    axis(1, at=1:26,labels=x) 

lines(sites$date,sgam$fit, lty = 1) 
lines(sites$date,sgam$fit + 1.96* sgam$se, lty = 2) 
lines(sites$date,sgam$fit - 1.96* sgam$se, lty = 2) 

GGPLOT2有一個解決方案(不介意as.date東西),但它給了我其他問題...

回答

0
sites <- read.table("349.txt", header = TRUE, sep = "\t", quote="\"", dec=".") 
p<-as.Date(sites$date, origin="1960-01-01") 
sgam1 <- gam(sites$y ~ s(sites$date)) 
sgam <- predict(sgam1, se=TRUE) 
plot(p,sites$y, xlab='Time', ylab='Counts') 
lines(p,sgam$fit, lty = 1) 
lines(p,sgam$fit + 1.96* sgam$se, lty = 2) 
lines(p,sgam$fit - 1.96* sgam$se, lty = 2) 

This Works!

0

使用origin=參數as.Date()指定一個特定的偏移:

R> as.Date(c(928, 928, 930), origin="1960-01-01") 
[1] "1962-07-17" "1962-07-17" "1962-07-19" 
R> 

一旦您的數據類型爲Date,您可以根據需要選擇格式化軸的選項。

+0

感謝您的輸入。我已經使用as.Date轉換了日期,但是實際的原始日期值是圖中顯示的 - 例如,x軸從〜14000:18000開始,這是1960年以來的天數。我希望它顯示這些年。 – Nate 2010-05-08 03:07:37

+0

顯示命令。如果你得到-14000:18000,那麼它就會轉換回數字,即你沒有保留日期。嘗試例如'format(as.Date(「1970-01-01」) - 365 * 2,「%Y」)',如預期的那樣產生1968年。 – 2010-05-08 03:23:45

+0

as.Date(網站$ date,origin =「1960-01-01」)是我用過的。我不知道爲什麼它會變回... – Nate 2010-05-08 03:27:18

相關問題