ggplot: Cover `facet_grid` title with rectangle

倾然丶 夕夏残阳落幕 提交于 2020-04-18 03:46:10

问题


This is an extension/hack to a similar question that I asked here.

I Created a graph in ggplot and I want to cover the titles of a facet_grid with a rectangle.

Using geom_rect I manged to spread rectangles over each facet. However, how can I spread the rectangles over the titles?

Current graph:

Expected graph:

Sample data and script:

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)

回答1:


As pointed out in the related post, one can now easily created nested facets with the ggnomics package, available on GitHub.

This does not quite exactly what you were asking here (annotating outside the plot area with rectangles that go across facets) but probably achieves what you want in the end... Annotating across facets would require another 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"))

Created on 2020-03-24 by the reprex package (v0.3.0)



来源:https://stackoverflow.com/questions/60827811/ggplot-cover-facet-grid-title-with-rectangle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!