I want to fill a histogram different colors based on date ranges. In the example below, the entire histogram is orange. Let's say I want fill dates 2012-03-01 to 2012-04-28 a different color and keep the rest orange.
library(ggplot2)
library(lubridate)
# random dates
# https://stackoverflow.com/questions/14720983/efficiently-generate-a-random-sample-of-times-and-dates-between-two-dates
randdate <- function(N, st="2012/01/01", et="2012/12/31") {
st <- as.POSIXct(as.Date(st))
et <- as.POSIXct(as.Date(et))
dt <- as.numeric(difftime(et,st,unit="sec"))
ev <- sort(runif(N, 0, dt))
rt <- st + ev
}
set.seed(42)
dat <- data.frame(y=sample(c(0:50), 1000, replace=TRUE),
date=randdate(1000))
dat$date <- ymd(substr(dat$date, 1, 10))
ggplot(dat,
aes(x=date)) +
geom_histogram(binwidth=400000,
fill="#E69F00",
colour="#E69F00") +
scale_x_datetime(labels=date_format("%m-%Y"),
breaks=date_breaks("1 year"))
Hadley's answer here suggests fill=..x..
, but I have not had luck getting it to work with dates. Any ideas?