6

I've got some issue when working on a plot with geom_area. I've got a data frame containing date and counts, like that:

dates <- c("02/01/00", "02/04/00", "02/07/00", "02/10/00", "02/01/01", "02/04/01", "02/07/01", "02/10/01")
dat <- data.frame(date=as.Date(dates, "%d/%m/%y"), count=(sample(1:8)))

I then aded a "month" variable:

dat["month"] <- month(dat$date)

And then my plot:

plot <- ggplot(data=dat, aes(x=date, y=count, group=month, fill=month)) + geom_area()

The result wouldn't be so bad, if it could understand, that it shouldn't fill an area from the first occurence of this month to the second one on the next year, but from this occurence to the one of the next month in the same year. (To understand better: the lines should be the same as the ones of the diagramm plot2 (see below), but be filled with different colors for each new month).

plot2 <- ggplot(data=dat, aes(x=date, y=count)) + geom_line()
zx8754
  • 52,746
  • 12
  • 114
  • 209
GaryDe
  • 492
  • 1
  • 5
  • 17
  • You want something like ggplot(data=dat, aes(x=date, y=count, group=1, fill=month)) + geom_area()`, but that's not allowed. You can't change the fill along a continuous ribbon. – Axeman Jul 18 '17 at 14:41
  • 1
    how about : `lst = lapply(1:(nrow(dat)-1), function(i) geom_ribbon(data=data.frame(x=dat$date[i:(i+1)], ymin=0, ymax=dat$count[i:(i+1)], fill=rep(dat$month[i]),2), aes(x=x,ymin=ymin, ymax=ymax, fill=fill))) ; ggplot(dat) + lst` – user20650 Jul 18 '17 at 16:19

1 Answers1

6

In the same line as the @user20659's comment but manipulating data:

dat["month"] <- as.factor(month(dat$date))
dat["df"] <- as.factor(dat$date)

dat2 <-data.frame(date=dat$date[-1],count=dat$count[-1], month=dat$month[-8],df=dat$df[-8])

dat3 <- rbind(dat,dat2)

ggplot(data=dat3, aes(x=date, ymax=count, ymin=0, group=df, fill=month)) + geom_ribbon()

Plot

Marcelo
  • 4,234
  • 1
  • 18
  • 18