首页 > 解决方案 > 在特定日期之间在 r 中进行 geom_rect 着色的更好方法

问题描述

我有一些时间序列数据,如下所示。

# A tibble: 396 x 4
   date       name    value binary_variable
   <chr>      <chr>   <dbl>           <dbl>
 1 1996-01-31 HAM1   0.0074              NA
 2 1996-02-29 HAM1   0.0193              NA
 3 1996-03-31 HAM1   0.0155              NA
 4 1996-04-30 HAM1  -0.0091              NA
 5 1996-05-31 HAM1   0.0076              NA
 6 1996-06-30 HAM1  -0.0039              NA
 7 1996-07-31 HAM1  -0.0231              NA
 8 1996-08-31 HAM1   0.0395              NA
 9 1996-09-30 HAM1   0.0147              NA
10 1996-10-31 HAM1   0.0288              NA

1列中有一些binary_variable。我想在1's时遮蔽时间序列数据active

到目前为止,我的尝试只是创建了灰线,但是我想要一个灰色块,在那里我可以开始alpha = 0.1工作(目前它被忽略了)。

数据和尝试:

data(managers)

# Firstly I create the data how I have it.
m <- managers %>% 
  as_tibble(rownames = NA) %>% 
  rownames_to_column("date") %>% 
  pivot_longer(cols = 2:ncol(.)) %>% 
  arrange(name) %>% 
  filter(name == "HAM1" | name == "HAM3" | name == "HAM4") %>% 
  mutate(
    binary_variable = case_when(
      date >= "1997-02-28" & date <= "1997-05-31" ~ 1,
      date >= "1999-08-31" & date <= "2000-04-30" ~ 1,
      date >= "2002-01-31" & date <= "2002-12-31" ~ 1,
      date >= "2005-01-31" & date <= "2006-04-30" ~ 1
    )
  )

# This is the part where I am stuck.
m %>% 
  ggplot(aes(x = date, y = value, group = name, color = name)) +
  geom_line() +
  geom_point() +
  geom_rect(data = m %>%                      
              filter(binary_variable == 1),
            aes(xmin = date, xmax = date, ymin = -Inf, ymax = Inf), color = "grey", alpha = 0.01)

标签: r

解决方案


推荐阅读