根据日期范围填充直方图 [英] fill histogram based on date ranges

查看:117
本文介绍了根据日期范围填充直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据日期范围填充直方图不同的颜色。在下面的例子中,整个直方图是橙色的。假设我想填充日期2012-03-01至2012-04-28不同的颜色,并保持橙色。

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"))

哈德利的回答此处建议 fill = .. x .. ,但我没有运气让它与日期一起工作。任何想法?

Hadley's answer here suggests fill=..x.., but I have not had luck getting it to work with dates. Any ideas?

推荐答案

如果您只是扩展包含 cut 函数,你会得到你想要的。

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")

这篇关于根据日期范围填充直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆