根据日期范围填充点数

时间:2014-10-11 21:12:02

标签: r ggplot2

我正在尝试根据相同的切割将previous answer on filling a histogram based on date cuts扩展为着色点。

library(ggplot2)
library(lubridate)
library(scales)

# 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, y=y, 
           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_point() +
  scale_x_datetime(labels=date_format("%m-%Y"),
                   breaks=date_breaks("1 year")) +
  scale_fill_manual(values=c("#E69F00", "#56B4E9", "#009E73"))

也是基于this answer的尝试,但减少&#34;削减&#34;。

ggplot(dat) + 
  geom_point(aes(x=date, y=y,
                 colour=x > as.POSIXct("2012-03-01"))) + 
  geom_line(colour="#999999", size=1) +
  scale_colour_manual(values=c("#56B4E9", "#009E73")) +
  ylab("Count") +
  theme_bw() +
  theme(axis.title.x = element_blank(),
        panel.background = element_blank(), 
        panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        axis.line = element_line(color = 'black'),
        title=element_text(size=9, face="bold"),
        legend.position="none")

1 个答案:

答案 0 :(得分:1)

首先,geom_point使用color美学,而非fill。接下来,我发现(对我而言)将分解的颜色分配给数据帧与尝试使ggplot调用更复杂更为有意义:

dat$col <- "during"
dat$col <- ifelse(dat$date < as.POSIXct("2012-03-01"), "before", dat$col)
dat$col <- ifelse(dat$date > as.POSIXct("2012-04-28"), "after", dat$col)
dat$col <- factor(dat$col, c("before", "during", "after"), ordered=TRUE)

ggplot(dat, aes(x=date, y=y, color=col)) +
  geom_point() +
  scale_x_datetime(labels=date_format("%m-%Y"),
                   breaks=date_breaks("1 year")) +
  scale_color_manual(values=c("#E69F00", "#56B4E9", "#009E73"))

enter image description here

相关问题