2014-10-09 39 views
1

我想根據日期範圍填充直方圖不同的顏色。在下面的例子中,整個直方圖是橙色的。假設我想填充日期2012-03-01至2012-04-28不同的顏色,並保持橙色。根據日期範圍填充直方圖

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

哈德利的答案here表明fill=..x..,但我還沒有運氣得到它與日期工作。有任何想法嗎?

回答

1

如果您只是擴展Hadley包含在cut函數中的示例,您將得到您想要的結果。

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

enter image description here

+0

謝謝,@MrFlick。以前,在使用'cut'之前,我可以運行以下命令來添加一個垂直線段:'geom_segment(x = as.numeric(ymd(「2012-05-27」)),y = 0,xend = as.numeric(YMD( 「2012-05-27」)),YEND = 20,線型= 1,顏色= 「#999999」)'。現在我收到一個錯誤,找不到'x'。我已經嘗試了'x'的幾種不同的格式,但是我還沒找到合適的格式。我怎樣才能將這一線段添加到你的答案中的情節? – 2014-10-09 03:44:31

+0

請注意,您不希望在'geom_segment'圖層中使用'fill ='美學,因此請將'aes()'移動到'geom_histogram'或在geom_segment中設置'inherit.aes = FALSE' ' – MrFlick 2014-10-09 03:49:39

+0

'inherit.aes = FALSE'它是。不知道這個選擇。很棒的解決 – 2014-10-09 03:52:16