Home > Net >  Add blank gap between specific geom_area using ggplot2
Add blank gap between specific geom_area using ggplot2

Time:11-16

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.

Edited data:

structure(list(date = c("2021-07-31", "2021-08-31", "2021-09-07", 
"2021-09-14", "2021-09-21", "2021-09-30", "2021-10-7", "2021-10-14", 
"2021-10-21", "2021-10-31", "2021-11-30", "2021-12-31", "2022-1-31", 
"2022-2-28"), 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, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L)), class = "data.frame", row.names = c(NA, 
-14L))

enter image description here

CodePudding user response:

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'll 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()

with new sample data

enter image description here

  • Related