I am trying to get ggplot to produce a histogram with bins which are 3 months wide. Not 90 days but 3 months. In terms of days, this is an unequal width binning. Note that tick marks at 3 month intervals works fine. It is the bin width that I am having problems with. There was quite a bit of discussion here but I could not find a resolution.
Understanding dates and plotting a histogram with ggplot2 in R
Here is a statement of the problem. Note that I could obviously aggregate the results outside of ggplot and then plot them, perhaps as factors in ggplot. But I was looking for an all ggplot solution.
set.seed(seed=1)
dts<-as.Date('2012-01-01') + round(365*rnorm(500))
dts<-data.frame(d=dts)
g<-ggplot(dts,aes(x=d, y=..count..))
#this isnt what I want. It is 90 days, not 3 months.
#Setting binwidth=' 3 months' also doesnt work
g + geom_histogram(fill='blue',binwidth=90) +
scale_x_date(breaks = date_breaks('3 months'), #seq(as.Date('2008-1-1'), as.Date('2012-3-1'), '3 month'),
labels = date_format("%Y-%m"),
limits = c(as.Date('2010-1-1'), as.Date('2014-1-1'))) +
opts(axis.text.x = theme_text(angle=90))
#this doesnt work either.
#get: stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.
# Error in `+.Date`(left, right) : binary + is not defined for Date objects
g + geom_bar(fill='blue') +
stat_bin(breaks=seq(as.Date('2010-1-1'), as.Date('2014-1-1'), '3 month')) +
scale_x_date(breaks = date_breaks('3 months'), #seq(as.Date('2008-1-1'), as.Date('2012-3-1'), '3 month'),
labels = date_format("%Y-%m"),
limits = c(as.Date('2010-1-1'), as.Date('2014-1-1'))) +
opts(axis.text.x = theme_text(angle=90))
Perhaps the answer is: ggplot will not create 3 month wide (or N month wide) bins.