如何在格子中创建堆积面积图?

时间:2019-06-12 21:35:14

标签: r plot lattice stacked-area-chart

考虑这个简单的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

我想使用lattice创建堆积面积图,其中timex轴上,并且var1var2堆积(在y轴)。

有可能这样做吗?

谢谢!

1 个答案:

答案 0 :(得分: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)) 

reprex package(v0.3.0)于2019-06-12创建