DJV
DJV

Reputation: 4873

ggplot: Cover `facet_grid` title with rectangle

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: enter image description here

Expected graph:

enter image description here

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)

Upvotes: 0

Views: 455

Answers (1)

tjebo
tjebo

Reputation: 23807

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)

Upvotes: 1

Related Questions