【问题标题】:R plot- SGAM plot counts vs. time - how do I get dates on the x-axis?R plot- SGAM 绘图计数与时间 - 如何在 x 轴上获取日期?
【发布时间】:2010-05-08 00:45:28
【问题描述】:

我想用实际日期(实际年份,1997,1998...2010)绘制这个与时间的关系。日期采用原始格式,ala SAS,自 1960 年以来的天数(因此为 as.date 转换)。如果我使用 as.date 将日期转换为变量 x,并绘制 GAM 图,则会出现错误。它适用于原始天数。但我希望情节显示年份(数据不等间距)。

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 的事情),但它给我带来了其他问题......

【问题讨论】:

    标签: r plot


    【解决方案1】:

    使用as.Date()origin= 参数来指定特定的偏移量:

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

    一旦您的数据具有 Date 类型,您就可以根据需要设置轴的格式。

    【讨论】:

    • 感谢您的意见。我已经使用 as.Date 转换了日期,但是实际的原始日期值显示在图表上 - 使得 x 轴从 ~14000:18000 开始,这是自 1960 年以来的天数。我希望它显示年。
    • 显示命令。如果你得到 -14000:18000 那么它会被转换回数字,即你没有保留日期。尝试例如 'format(as.Date("1970-01-01")-365*2, "%Y")' 这将按预期产生 1968。
    • as.Date(sites$date, origin="1960-01-01") 是我使用的。我不知道为什么它被转换回来......
    【解决方案2】:
    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)
    

    这行得通!

    【讨论】:

      猜你喜欢
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      • 2014-08-20
      • 1970-01-01
      • 2016-12-14
      • 1970-01-01
      • 2011-05-17
      • 1970-01-01
      相关资源
      最近更新 更多