【问题标题】:facet_wrap: mark (color border, line and title) one specific plotfacet_wrap:标记(颜色边框,线条和标题)一个特定的情节
【发布时间】:2018-06-04 10:39:31
【问题描述】:

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

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

【问题讨论】:

  • 恐怕there's no easy solution。最简单的方法是创建 N 个单图并将它们与 eggggpubrcowplot 包组合。

标签: r plot ggplot2 colors facet-wrap


【解决方案1】:

正如 cmets 中所述,按照您的建议去做并不容易。这是一个人可能会做的事情。在这里,我创建了一个示例数据框,并同时加载了 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)

得到:

【讨论】:

  • 这是一个写得很好的解决方案,并且执行得很好。它的工作原理与您的示例完全相同。做得好,谢谢!
  • 你知道如何修改条形背景左边框的颜色吗?这会修改所有边框,但不仅仅是一个: g$grobs[[51]]$grobs[[1]]$children[[1]]$gp$col
猜你喜欢
  • 2015-06-22
  • 2016-09-15
  • 2020-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-19
  • 2019-01-28
  • 2011-09-25
相关资源
最近更新 更多