3

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

Mataunited18
  • 598
  • 1
  • 7
  • 20

1 Answers1

4

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

Jack Brookes
  • 3,720
  • 2
  • 11
  • 22