0
votes

I have a dataframe df much like the following:

      value group      dates
      1     1           2020-01-01
      5     1           2020-01-02
      6     1           2020-01-03
      1     2           2020-01-04
      3     2           2020-01-05
      1     2           2020-01-06

I need to make a stacked area chart showing the total sum of values, like so:

ggplot(df,aes(x=dates,y=cumsum(value)))+geom_area()

which results in this:

enter image description here

What I need is to fill the plot with colors according to group, like so:

enter image description here

but, I have not been able to find out how to do this. I am sure it is trivial, but unfortunately the answer eludes me.

What I have tried is just adding fill, like so ggplot(df,aes(x=dates,y=cumsum(value),fill=as.factor(group)))+geom_area(position = 'stack') but this results in the following

enter image description here

1

1 Answers

1
votes

This could be achieved like so:

  1. Expand the dataset so that you have obs. for each group on each date using e.g. tidyr::complete
  2. Compute the cumulative sum by group
library(tidyverse)

df <- read.table(text = "value group      dates
      1     1           2020-01-01
      5     1           2020-01-02
      6     1           2020-01-03
      1     2           2020-01-04
      3     2           2020-01-05
      1     2           2020-01-06", header = TRUE)

df %>% 
  tidyr::complete(group, dates, fill = list(value = 0)) %>% 
  arrange(group, dates) %>%
  group_by(group) %>% 
  mutate(dates = as.Date(dates),
         value = cumsum(value)) %>% 
  ggplot(aes(x=dates,y = value, fill = factor(group), group = rev(group))) + geom_area(position = 'stack')