如何更改格子图中的填充颜色?

时间:2019-06-13 11:35:41

标签: r lattice

考虑此示例

library(tibble)
library(lubridate)
library(lattice)
library(latticeExtra)

df <- 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')),
       variable = c('a','a','a','b','b','b'),
       value = c(1,2,3,0,0,2))

# A tibble: 6 x 3
  time       variable value
  <date>     <chr>    <dbl>
1 2019-01-01 a            1
2 2019-01-02 a            2
3 2019-01-03 a            3
4 2019-01-01 b            0
5 2019-01-02 b            0
6 2019-01-03 b            2

我正在尝试从ggplot再现堆积面积图

  df %>% ggplot(aes(x = time, y = value, fill = variable)) +
  geom_area()

enter image description here

我快到了,但是在下面的示例中着色是错误的

  df  %>%  group_by(time) %>% 
  mutate(value = ifelse(variable == 'a', sum(value), value)) %>% 
  ungroup() %>% 
  xyplot(value~time, data = ., group=variable,
     panel=function(x,y,...){
     panel.xyarea(x,y,...)
     panel.xyplot(x,y,...)},
     col=c("red","blue"),
     alpha=c(0.8,0.4)) 

enter image description here

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:1)

这是使用simpleTheme的一种解决方案:

df  %>%  group_by(time) %>% 
     mutate(value = ifelse(variable == 'a', sum(value), value)) %>% 
     ungroup() %>% 
     xyplot(value~time, data = ., group=variable,
            panel=function(x,y,...){
                panel.xyarea(x,y,...)
                panel.xyplot(x,y,...)}, par.settings=simpleTheme(col=c("red", "blue")))

我希望这是您想要的。