Manually add color to geom_area in places with x variables on multiple faces

This is a rough approximation dfI'm working with:

months <- 1:12
age_y <- rep(0:2, 4)
counts <- c(659, 508, 430, 303, 201, 180, 203, 318, 401, 500, 790, 630)
df <- cbind.data.frame(months, age_y, counts)
ggplot(df, aes(x = months, y = counts)) + geom_area() + facet_grid(.~age_y)

What I'm trying to do is colored areas in different faces of different colors. In particular, with the dummy data above, I would like to color the area:

From x = 5up x = 6.25in the facet 0red

From x = 6.25to x = 10to facet 0blue

From x = 6.25up x = 7.5in the facet 1red

From x = 7.5to x = 10in facet 1blue

From x = 7.5up x = 8.75in the facet 2red

From x = 8.75to x = 10in facet 2blue

+4
source share
1 answer

I would like to color the area:
From x = 5 to x = 6.25 in facet 0 red
From x = 6.25 to x = 10 in facet 0 blue
From x = 6.25 to x = 7.5 in facet 1 red

library(ggplot2)
months <- 1:12
age_y <- rep(0:2, 4)
counts <- c(659, 508, 430, 303, 201, 180, 203, 318, 401, 500, 790, 630)
df <- cbind.data.frame(months, age_y, counts)
ggplot(df, aes(x = months, y = counts)) + geom_area() + facet_grid(.~age_y) -> p

f <- lapply(split(df[,c("months", "counts")], df$age_y), function(dat) approxfun(dat$months, dat$counts) )
p + scale_fill_identity() + 
  mapply(function(xmin,xmax,facet,col,res=.001) 
  geom_area(
    data = data.frame(
      age_y=facet, 
      months = seq(xmin, xmax, res), 
      counts = f[[facet]](seq(xmin, xmax, res)), 
      col = col), 
    aes(fill=col)
  ), c(5,6.25,6.25),c(6.25,10,10),c("0","0","1"),c("red","blue", "blue"))

... ..:

enter image description here

+4

All Articles