Search code examples
rdataframeggplot2stacked-area-chart

Stacked area chart in R


I want to create a stacked area chart for the following data:

enter image description here

And the data continues a bit further.

I am using ggplot and tried with:

Dates <- seq.Date(as.Date("2010-03-01"), Sys.Date(), "month")
ggplot(output_2, aes(x = Dates, y = ??, fill = ??)) + geom_area()

I do not know what to input for y and fill. I want the graph to be stacked with x1,x2,x3,x4 and a curve for x5.

Any help will be much appreciated.

Thank you!


Solution

  • This may helps.

    for dummy data according to image

    dummy <- data.frame(
      x1 = c(-0.2510,-0.1889,-0.0440,-0.0134,0.0044,-0.0962),
      x2 = c(-0.1177,-0.1265,-0.1454,-0.2242,-0.2268,-0.1653),
      x3 = c(0.1992,0.2063,0.2026,0.2215,0.2205,0.1980),
      x4 = c(0.2316,0.2297,0.1811,0.0676,0.0656,0.1412),
      x5 = c(0.0621,0.1206,0.1943,0.0515,0.0637,0.0777)
    )
    
    dummy$date <- seq.Date(as.Date("2021-04-01"), Sys.Date(), "month")
        dummy %>%
      melt(id.vars = "date") %>% 
      ggplot(aes(x = date, y = value, fill = variable, group = variable)) + 
      geom_area(colour = NA, alpha = 0.5)
    

    enter image description here

    Code for your data(maybe)

    output_2$Dates <- seq.Date(as.Date("2010-03-01"), Sys.Date(), "month")
    output_2 %>%
      melt(id.vars = "Dates") %>% 
      ggplot(aes(x = Dates, y = value, fill = variable, group = variable)) + 
      geom_area(colour = NA, alpha = 0.5)