【问题标题】:ggplot: Cover `facet_grid` title with rectangleggplot:用矩形覆盖`facet_grid`标题
【发布时间】:2020-07-04 18:10:44
【问题描述】:

这是我向here 提出的类似问题的扩展/破解。

我在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)

【问题讨论】:

标签: r ggplot2 facet-grid


【解决方案1】:

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

这并不完全正是您在此处所要求的(在绘图区域之外用跨越多面的矩形进行注释),但最终可能实现了您想要的...... 跨方面注释将需要另一个 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 年 3 月 24 日创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    相关资源
    最近更新 更多