Geom_area is filled with different colors

I have a problem while working on a plot with geom_area. I have a data frame containing a date and quantity, for example:

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

Then I applied the 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 would not be so bad if he could understand that he should not fill the field from the first appearance of this month to the second in the next year, but from this incident to one of the next month in the same year. (To better understand: the lines should be the same as the plot2 diagrams (see below), but filled with different colors for each new month).

plot2 <- ggplot(data=dat, aes(x=date, y=count)) + geom_line()
+4
source share
1 answer

On the same line as @ user20659 comment, but manipulating the 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

+4

Source: https://habr.com/ru/post/1681700/


All Articles