Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading