Search code examples
rggplot2chartsstacked-area-chart

R: Create a stacked area plot of time series in ggplot2


I have a data frame that is a percentage allocation for each variable. There are four variables where the sum of the rows are equal to 1. Here is a example output of the data frame:

dates       A   B   C   D
1997-01-01  0.2 0.2 0.5 0.1 
1997-02-01  0.3 0.2 0.4 0.1
1997-03-01  0.1 0.3 0.2 0.4
...         ... ... ... ...
2017-12-01  0.2 0.2 0.1 0.5

How can I create a similar stacked area plot like where the x-axis shows the years, and y-axis is from 0 to 1 (from https://ggplot2.tidyverse.org/reference/geom_density.html):

enter image description here

My attempt at following the instructions produced this, which is not exactly what I am looking for:

enter image description here

I get the error message:

Error: A:D must evaluate to column positions or names, not a double vector

In addition: Warning messages:

1: In x:y : numerical expression has 252 elements: only the first used

2: In x:y : numerical expression has 252 elements: only the first used


Solution

  • I guess you want area, not density. Also you want to reshape your data to a long format.

    library(tidyverse)
    
    df <- read.table(text = "
    dates       A   B   C   D
    1997-01-01  0.2 0.2 0.5 0.1 
    1997-02-01  0.3 0.2 0.4 0.1
    1997-03-01  0.1 0.3 0.2 0.4
    ", header = TRUE)
    
    df %>% 
      mutate(dates = as.Date(dates)) %>% 
      gather(variable, value, A:D) %>% 
      ggplot(aes(x = dates, y = value, fill = variable)) +
      geom_area()
    

    enter image description here