1

Consider this simple tibble

tibble(time = c(ymd('2019-01-01'),
                ymd('2019-01-02'),
                ymd('2019-01-03'),
                ymd('2019-01-04'),
                ymd('2019-01-05')),
       var1 = c(1,2,3,4,5),
       var2 = c(2,0,1,2,0))
# A tibble: 5 x 3
  time        var1  var2
  <date>     <dbl> <dbl>
1 2019-01-01     1     2
2 2019-01-02     2     0
3 2019-01-03     3     1
4 2019-01-04     4     2
5 2019-01-04     5     0

I would like to create a stacked area chart using lattice, where time is on the x axis and var1 and var2 are stacked (on the y axis) over time.

Is it possible to do so?

Thanks!

M--
  • 25,431
  • 8
  • 61
  • 93
ℕʘʘḆḽḘ
  • 18,566
  • 34
  • 128
  • 235
  • 1
    no, not cumulative. at time t you plot (var1) and (var1+var2). really something like https://www.r-graph-gallery.com/136-stacked-area-chart/ – ℕʘʘḆḽḘ Jun 12 '19 at 22:03
  • Follow up questions: https://stackoverflow.com/questions/56582808/multiarea-chart-in-lattice and https://stackoverflow.com/questions/56579576/how-to-change-the-fill-color-in-a-lattice-plot for future reference – M-- Jun 13 '19 at 14:32

1 Answers1

1
library(tibble)
library(lubridate)
library(lattice)
library(latticeExtra)
library(reshape2)


df1 <- tibble(time = c(ymd('2019-01-01'),
                       ymd('2019-01-02'),
                       ymd('2019-01-03'),
                       ymd('2019-01-04'),
                       ymd('2019-01-05')),
              var1 = c(1,2,3,4,5),
              var2 = c(2,0,1,2,0))

df2 <- df1
df2$var2 <- df2$var2 + df2$var1
df2 <- melt(df2, id.vars = "time")


xyplot(value~time, df2, group=variable,
       panel=function(x,y,...){
             panel.xyarea(x,y,...)
             panel.xyplot(x,y,...)},
      col=c("red","blue"),
      alpha=c(0.8,0.4)) 

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

M--
  • 25,431
  • 8
  • 61
  • 93
  • @ℕʘʘḆḽḘ ;) I know you can add two `lattice` plots together as well (simply like `p1+p2`) using `latticeExtra` but I couldn't get that to work here. – M-- Jun 12 '19 at 22:34
  • its ok. do you know if a secondary axis can be added here? – ℕʘʘḆḽḘ Jun 12 '19 at 22:35
  • @ℕʘʘḆḽḘ just left my desk, on my cell now. Not off the top of my head, but I'm pretty sure it's possible. – M-- Jun 12 '19 at 22:45
  • funnily enough, the `col` arguments applies to the dots, not to the area. do you think we can control the area color as well? – ℕʘʘḆḽḘ Jun 13 '19 at 00:18
  • @ℕʘʘḆḽḘ use fill maybe – M-- Jun 13 '19 at 00:18
  • @ℕʘʘḆḽḘ use it as a panel argument. – M-- Jun 13 '19 at 02:10
  • I tried. didnt work I get `> panel.xyarea(x,y,...,col =c("red","blue")) Error: '...' used in an incorrect context` – ℕʘʘḆḽḘ Jun 13 '19 at 02:18
  • @ℕʘʘḆḽḘ I used fill inside the layout and did not get an error but still no actual change of color. This can be another question as a follow up. – M-- Jun 13 '19 at 02:44