Search code examples
rggplot2geom-area

Changing the color of the area under the curve according to a categorical variable (geom_area)


I am trying to draw a curve (with geom_area) where the area under the curve is changing according to a third variable.

Here is a reproducible example:

data <- data.frame(
  time = seq(1,10),
  activity = c(43.59675 ,18.15803 ,26.59981 ,72.64358 ,20.68794, 86.13841, 47.64718, 83.94334 ,32.33138, 81.70798),
  space = c(1 ,3 ,3 ,1 ,2 ,3 ,2 ,2 ,3 ,1)
)

data$space <- as.character(data$space)
ggplot(data,
       aes (x = time, y = activity)) + geom_area()

The result is here:

enter image description here

What I want is to color this black area under the curve according to the space variable. Trying something like the below code give a very strange curve (check it out here:

enter image description here

ggplot(data,aes (x = time, y = activity, fill = space)) + geom_area()

Any help?


Solution

  • First you need some data manipulation! Then you can use geom_ribbon().

    data$space <- as.factor(data$space)
    data$time <- as.factor(data$time)
    data$df <- as.factor(data$time)
    
    data2 <- data.frame(time=data$time[-1], activity=data$activity[-1], space=data$space[-10], df=data$df[-10])
    data3 <- rbind(data,data2)
    
    ggplot(data3, aes (x = time, ymax = activity, ymin=0, group=df, fill=space)) + 
      geom_ribbon()
    
    

    enter image description here