向网格中的每个面添加一条线

Add a line to each facet in a grid

假设我有以下数据框:

  dates          types vals
1 2018-02-01     a     10
2 2018-03-01     a     11
3 2018-04-01     a     12
4 2018-05-01     b     20
5 2018-06-01     b     21
6 2018-07-01     b     22
7 2018-08-01     c     30
8 2018-09-01     c     31
9 2018-10-01     c     32

我将其可视化为具有 3 个方面的网格(每种类型一个:a、b 和 c),具有共同的 X 轴(日期):

gg <- ggplot(df, aes(x = dates, y = vals)) + 
  geom_line(aes(color = df$types)) +
  geom_point() +
  facet_grid(types ~ ., scales = "free_y") +
  scale_color_manual(values =c("blue", "orange", "green"))

现在我想为每个面添加一条水平线,这样每个面都有自己的 y 轴截距。基于类似的问题,我尝试创建一个包含一列截距的数据框:

lower = seq(10,30,10); upper = seq(12,32,10)
bounds <- data.frame(lower, upper)

并使用 geom_hline 添加:

gg + geom_hline(aes(yintercept = lower), data = bounds, color = 'red')

但结果是每个方面都有三行,而不是它自己的行(我还想添加一行带有 upper 列,但我想解决方案是对称的)。

您需要添加 lower 规范来匹配分面数据,如下所示:

library('dplyr')
df <- df %>% mutate(lower = rep(c(10,20,30), each =3))
df
       dates types vals lower
1 2018-02-01     a   10    10
2 2018-03-01     a   11    10
3 2018-04-01     a   12    10
4 2018-05-01     b   20    20
5 2018-06-01     b   21    20
6 2018-07-01     b   22    20
7 2018-08-01     c   30    30
8 2018-09-01     c   31    30
9 2018-10-01     c   32    30

然后像以前一样指定绘图,并像这样在带有 lower 列的更改后的 df 上添加 geom_hline - 像这样:

gg + geom_hline(aes(yintercept = lower), color = 'red')

然后你会得到这样的东西:

尽管有一个 , here is one way of ,就像 OP 在评论中要求的那样。

首先,查看 types 在数据帧 bounds 中的位置。

cbind(bounds, types = c('a', 'b', 'c'))
#  lower upper types
#1    10    12     a
#2    20    22     b
#3    30    32     c

与原来合并后的结果是什么df

merge(cbind(bounds, types = c('a', 'b', 'c')), df)
#  types lower upper      dates vals
#1     a    10    12 2018-02-01   10
#2     a    10    12 2018-03-01   11
#3     a    10    12 2018-04-01   12
#4     b    20    22 2018-05-01   20
#5     b    20    22 2018-06-01   21
#6     b    20    22 2018-07-01   22
#7     c    30    32 2018-08-01   30
#8     c    30    32 2018-09-01   31
#9     c    30    32 2018-10-01   32

似乎是对的,就在 types 需要的地方。
所以绘制它,调整问题中的代码。

gg + geom_hline(data = merge(cbind(bounds, types = c('a', 'b', 'c')), df),
             aes(yintercept = lower), 
             color = 'red')