我正在尝试使用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)
但是,当我运行print时,出现以下错误:
Error in `+.Date`(left, right) : binary + is not defined for Date objects
如果我正确读取此内容,则没有为Date
个对象定义加号运算符,因此无法执行此类分类?
答案 0 :(得分:3)
当我在其他情况下从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')))
答案 1 :(得分:1)
在我看来,如果你只是先转换数据,然后将它传递给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
答案 2 :(得分:1)
我可以按如下方式重现您的错误:
> 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
个对象定义的。