0

I am trying to expand a previous answer on filling a histogram based on date cuts to coloring points based on the same 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"))

Also an attempt based on this answer, but with fewer "cuts".

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")
Community
  • 1
  • 1
Eric Green
  • 7,385
  • 11
  • 56
  • 102
  • You haven't really said what the problem is, but you use the `color` aesthetic with points, not `fill`. – jlhoward Oct 11 '14 at 21:26

1 Answers1

2

First, geom_point uses the color aesthetic, not fill. Next, I find that it's makes more sense (to me) to assign the factored colors to the data frame vs try to make the ggplot calls more complex:

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

hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
  • thanks, @hrbrmstr. this works. so does changing `fill` and `scale_fill_manual` to `colour` and `scale_colour_manual`. thanks for pointing that out. – Eric Green Oct 11 '14 at 22:30