ggplot:用矩形覆盖“facet_grid”标题

ggplot: Cover `facet_grid` title with rectangle

这是 extension/hack 我问过的一个类似问题

我在 ggplot 中创建了一个图表,我想用一个矩形覆盖 facet_grid 的标题。

使用 geom_rect 我设法在每个面上展开矩形。但是,如何将矩形散布在标题上?

当前图表:

预期图表:

示例数据和脚本:

library(tidyverse)

df <- head(mtcars, 5)

plot <- df %>% 
  ggplot(aes(gear, disp)) + 
  geom_bar(stat = "identity") + 
  facet_grid(~am + carb,
             space = "free_x", 
             scales = "free_x") +
  ggplot2::theme(
    panel.spacing.x = unit(0,"cm"), 
    axis.ticks.length=unit(.25, "cm"), 
    strip.placement = "outside",
    legend.position = "top",
    legend.justification = "center",
    legend.direction = "horizontal",
    legend.key.size = ggplot2::unit(1.5, "lines"),
    # switch off the rectangle around symbols
    legend.key = ggplot2::element_blank(),
    legend.key.width = grid::unit(2, "lines"),
    # # facet titles
    strip.background = ggplot2::element_rect(
      colour = "black",
      fill = "white"),
    panel.background = ggplot2::element_rect(
      colour = "white",
      fill = "white"), 
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank())

plot + 
  geom_rect(aes(xmin=2.4, xmax=2.7, ymin=400, ymax=300),
            color="black", fill="white") +
  geom_text(aes(x = 2.5, y = 400, label="world"), size=2)

正如相关 post 中所指出的,现在可以使用 ggnomics 包轻松创建嵌套的 facet,在 GitHub 上可用。

这并不完全您在这里问的(在绘图区域外用横跨各个方面的矩形进行注释)但最终可能实现您想要的... 跨方面注释需要另一个 grob hack...

#devtools::install_github("teunbrand/ggnomics")
  library(ggnomics)
#> Loading required package: ggplot2
  library(tidyverse)

  mydat<- head(mtcars, 5)
  mydat %>% 
    ggplot(aes(gear, disp)) + 
    geom_bar(stat = "identity") + 
    facet_nested(~am + carb) +
    theme(panel.spacing.x = unit(0,"cm"), 
          axis.ticks.length=unit(.25, "cm"), 
          strip.placement = "inside",
          strip.background = element_rect( colour = "black", fill = "white"),
          panel.background = element_rect( colour = "black", fill = "white"))

reprex package (v0.3.0)

于 2020-03-24 创建