代码之家  ›  专栏  ›  技术社区  ›  DrewConway

在时间序列的stat\u bin中使用seq.Date作为中断

  •  5
  • DrewConway  · 技术社区  · 15 年前

    我正在尝试使用 stat_bin 中的函数 ggplot2

    month.breaks<-seq.Date(from=min(afg$DateOccurred),to=max(afg$DateOccurred),by="month")  # All months, for breaks
    report.region<-ggplot(afg,aes(x=DateOccurred))+stat_bin(aes(y=..density..,fill=Type),breaks=month.breaks)+facet_wrap(~Region)
    print(report.region)
    

    Error in `+.Date`(left, right) : binary + is not defined for Date objects
    

    如果我读对了,加号运算符没有定义 Date

    3 回复  |  直到 15 年前
        1
  •  1
  •   nullglob    15 年前

    我可以把你的错误重现如下:

    > break.dates <- seq.Date(from=as.Date('2001-01-01'),
                              to=as.Date('2001-04-01'),
                              by="month") 
    > break.dates
    [1] "2001-01-01" "2001-02-01" "2001-03-01" "2001-04-01"
    ## add an offset, which increases the dates by a day
    > break.dates + 1
    [1] "2001-01-02" "2001-02-02" "2001-03-02" "2001-04-02"
    ## try to add two date objects together - this does not make sense!
    > break.dates + break.dates
    Error in `+.Date`(break.dates, break.dates) :
      binary + is not defined for Date objects
    

    把两个日期加在一起是没有意义的,因为日期表上没有自然的“零”。然而 + Date

        2
  •  3
  •   sus    8 年前

    在其他情况下,当我从ggplot2中得到这个错误时,我就可以在用于中断的序列周围使用as.numeric()了。例如,

    library(lubridate)
    library(ggplot2)
    library(scales)
    
    somedates <- ymd(20130101) + ddays(runif(100, 0, 364)) #generate some fake event dates
    somedatesformatted <- data.frame(Dates=as.Date(somedates)) #format them as data ggplot likes
    monthbins <- as.numeric(seq(as.Date('2013-01-01'), as.Date('2014-01-01'), '1 month')) # generate breaks for binning event dates and wrap in as.numeric()
    
    ggplot(somedatesformatted, aes(x=Dates)) + 
        stat_bin(breaks=monthbins) +
        ylab("Events per Month") +
        ylim(c(0,30)) +
        scale_x_date(breaks = '1 month',
                 labels = date_format("%b"),
                 limits = c(as.Date('2013-01-01'), as.Date('2013-12-31')))
    
        3
  •  1
  •   doug    15 年前

    在我看来,如果你先变换数据,你也能得到同样的结果, 将其传递给plot方法。

    例如(以月份为单位的时间序列数据按年份分类):

    data(AirPassengers)   # time series in months (supplied w/ default R install)
    AP = AirPassengers
    library(xts)
    X = as.xts(AP)      # need xts object to pass to xts binning method
    ndx = endpoints(X, on="years")    # binning method requires indices for desired bin freq
    X_yr = period.apply(x=X, INDEX=ndx, FUN=sum)   # X_yr is the binned data