Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

geom_area fill with different colors

Tags:

r

ggplot2

fill

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()
like image 337
GaryDe Avatar asked Jul 18 '17 12:07

GaryDe


1 Answers

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

like image 85
Marcelo Avatar answered Nov 12 '22 12:11

Marcelo