Add blank gap between specific geom_area using ggplot2

With sample and code below, I’m trying to reproduce the effect of an image as shown in the end of this question:

library(magrittr)
library(dplyr)
library(ggplot2)

df <- structure(list(date = structure(c(18901, 18902, 18903, 18904, 
18905, 18906, 18907, 18908, 18909, 18910, 18911, 18912, 18913, 
18914), class = "Date"), value = c(190.3, 174.9, 163.2, 168.4, 
168.6, 168.2, 163.5, 161.6, 172.9, 166.5, 175.2, 197.7, 212.1, 
177.9), type = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 
3L, 3L, 3L)), row.names = c(NA, -14L), class = "data.frame")
df$type <- as.factor(df$type)
# df$date <- as.Date(df$date)

df %>%
  group_by(type) %>%
  filter(row_number() == 1) %>%
  ungroup() %>%
  mutate(type = lag(type),
         date = date - 0.0001) %>% # w/o this the values stack at boundaries
  bind_rows(df) %>%
  ggplot(aes(x=date, y=value, group=type, 
            color = type, fill = type)) + 
  geom_area(alpha=0.4) +
  scale_color_manual(values=c("1" = "gray", "2" = "red", "3" = "blue"), 
                     aesthetics = c("color", "fill"), name = "type") +
  theme_bw()

Is it possible I could add a blank gap between data areas of type 1 and type 2 as show in the example plot?

enter image description here

How could I acheive that with ggplot2? Thanks.

enter image description here

>Solution :

2nd approach

enter image description here

library(data.table)
library(ggplot2)
#make it data.table. order by date
setDT(df, key = "date")
# what types do you want to 'extend' to the next type?
# in this example, you''l only want to 'extend' type == 1
types.extend <- c(1)
# select the first row from each type
new.values <- df[, .SD[1], by = .(type)][, type := shift(type, type = "lag")][type %in% types.extend,]
# bind the new value to your original data
df <- rbind(df, new.values)
ggplot(data = df, 
       aes(x=date, y=value, group=type, color = type, fill = type)) + 
  geom_area(alpha=0.4, position = "identity") +
  scale_color_manual(values=c("1" = "gray", "2" = "red", "3" = "blue"), 
                     aesthetics = c("color", "fill"), name = "type") +
  theme_bw()

Leave a Reply