Search code examples
rggplot2plotlatticestacked-area-chart

multiarea chart in lattice


I am pushing lattice to its limits.

Consider this example

tibble(time = c(ymd('2019-01-01'),
                      ymd('2019-01-02'),
                      ymd('2019-01-03'),
                      ymd('2019-01-01'),
                      ymd('2019-01-02'),
                      ymd('2019-01-03'),
                      ymd('2019-01-01'),
                      ymd('2019-01-02'),
                      ymd('2019-01-03')),
             variable = c('a','a','a','b','b','b', 'c','c','c'),
             value = c(1,2,3,0,0,2,2,4,3)) %>% 
  ggplot(aes(x = time, y = value, fill = variable)) + geom_area()

enter image description here

Using the nice solution in how to create a stacked area chart in lattice? does not work here, perhaps because we have multiple areas.

Can we still do it with lattice? Thanks!


Solution

  • library(dplyr)
    library(lubridate)
    library(lattice)
    library(latticeExtra)
    
    df1 <- tibble(time = c(ymd('2019-01-01'),
                           ymd('2019-01-02'),
                           ymd('2019-01-03'),
                           ymd('2019-01-01'),
                           ymd('2019-01-02'),
                           ymd('2019-01-03'),
                           ymd('2019-01-01'),
                           ymd('2019-01-02'),
                           ymd('2019-01-03')),
                  variable = c('a','a','a','b','b','b', 'c','c','c'),
                  value = c(1,2,3,0,0,2,2,4,3))
    
    df2 <- df1 %>% group_by(time) %>% mutate(val=cumsum(value))
    
    xyplot(val~time, df2, group=variable,
           panel=function(x,y,...){
             panel.xyarea(x,y,...)
             panel.xyplot(x,y,...)},
           alpha=c(0.9,0.6,0.3)) 
    

    Created on 2019-06-13 by the reprex package (v0.3.0)