fill histogram based on date ranges

匿名 (未验证) 提交于 2019-12-03 09:06:55

问题:

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?

回答1:

If you just extend the example Hadley included with the cut function you'll get what you want.

ggplot(dat,    aes(x=date,         fill=cut(..x..,         breaks=c(min(..x..), as.POSIXct("2012-03-01"), as.POSIXct("2012-04-28"), max(..x..)),        labels=c("before","during","after"), include.lowest=TRUE)    )) +    geom_histogram(binwidth=400000) +    scale_x_datetime(labels=date_format("%m-%Y"),                     breaks=date_breaks("1 year")) +    scale_fill_discrete(name="Range") 



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!