Dates of histograms with unequal cells in ggplot

I am trying to get ggplot to create a histogram with cells 3 months wide. Not 90 days, but 3 months. In terms of days, this is uneven width binning. Please note that marks with an interval of 3 months work fine. I have a problem with bin width. 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 description of the problem. Note that I could obviously aggregate the results outside of ggplot and then build them, perhaps as factors in ggplot. But I was looking for the whole 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 (or N month wide) bins.

+5
source share
1 answer

, stat_bin . , . , geom_bar, stat_bin, . :

g + stat_bin(breaks=as.numeric(seq(as.Date('2010-1-1'), 
                                   as.Date('2014-1-1'), '3 month')),
             fill = "blue",
             position = "identity") +
    scale_x_date(breaks = date_breaks('3 months'),
                 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))

enter image description here

, breaks stat_bin as.numeric. , position="identity" stat_bin, ( , ).

+3

All Articles