facet_wrap: 标记(颜色边框、线条和标题)一个特定的图

facet_wrap: mark (color border, line and title) one specific plot

是否可以用 ggplot2 标记 facet_wrap 的特定图?

假设我有一个 3x3 facet_wrap 情节,我想通过给它一个标记中间的情节 (i=2,j=2)红色边框、红色线条颜色和红色 title-color。我该如何以一种既方便又方便的方式做到这一点?

如评论中所述,按照您的建议进行操作并不简单。这是一个人可能会去做的事情。在这里,我创建了一个示例数据框,并加载了 ggplot2grid 包。

library(ggplot2)
library(grid)

set.seed(123)
df <- data.frame(f = rep(LETTERS[1:9], 3), x = rnorm(27), y = rnorm(27))

现在,我创建基本情节。红线是最简单的:我们将 colour 美学映射到我们用于刻面的变量,并在 scale_colour_manual:

中设置颜色
p <- ggplot(df, aes(x, y, colour = f == "E")) +
  geom_line() +
  scale_colour_manual(guide = FALSE, values = c("black", "red")) +
  facet_wrap("f")

剩下的,我们必须手动编辑情节。我们生成 plot grob 并检查它:

g <- ggplotGrob(p)
g
# TableGrob (21 x 15) "layout": 62 grobs
#     z         cells        name                                           grob
# 1   0 ( 1-21, 1-15)  background               rect[plot.background..rect.5921]
# 2   1 ( 7- 7, 4- 4)   panel-1-1                      gTree[panel-1.gTree.5502]
# ...
# 6   1 (12-12, 8- 8)   panel-2-2                      gTree[panel-5.gTree.5562]
# ...
# 51  2 (11-11, 8- 8) strip-t-2-2                                  gtable[strip]
# ...
# 62 10 (20-20, 4-12)     caption          zeroGrob[plot.caption..zeroGrob.5919]

感兴趣的 grobs 是数字 6 和 51,分别对应于中心面板及其面板条。检查 grob 编号 6,我们看到以下内容:

str(g$grobs[[6]])
# List of 5
#  $ name         : chr "panel-5.gTree.5562"
#  ...
#  $ children     :List of 5
#   ..$ grill.gTree.5560           :List of 5
#   .. ..$ name         : chr "grill.gTree.5560"
# ...
#   .. ..$ children     :List of 5
#   .. .. ..$ panel.background..rect.5551      :List of 10
# ...
#   .. .. .. ..$ gp    :List of 4
#   .. .. .. .. ..$ lwd : num 1.42
#   .. .. .. .. ..$ col : logi NA
#   .. .. .. .. ..$ fill: chr "grey92"
#   .. .. .. .. ..$ lty : num 1
#   .. .. .. .. ..- attr(*, "class")= chr "gpar"
# ...
#  - attr(*, "class")= chr [1:3] "gTree" "grob" "gDesc"

注意 col 元素。我们给这个元素赋值red

g$grobs[[6]]$children[[1]]$children[[1]]$gp$col <- "red"

检查 grob 51(结构略有不同),我们做同样的事情:

g$grobs[[51]]$grobs[[1]]$children[[2]]$children[[1]]$gp$col <- "red"

这就是我们需要做的全部。尽管检查 grob 结构需要一些努力,但进行修改并不需要那么多代码。总而言之,我们需要做的就是:

g <- ggplotGrob(p)
g$grobs[[6]]$children[[1]]$children[[1]]$gp$col <- "red"
g$grobs[[51]]$grobs[[1]]$children[[2]]$children[[1]]$gp$col <- "red"
grid.draw(g)

得到: