Search code examples
rggplot2facet-grid

get rid of empty panels in the first row of facet_grid


I was trying to use facet_grid to lay out panels, for example,

library(tidyverse)
library(lubridate)
economics %>%
  filter(date >= ymd(19680101)) %>% 
  mutate(
    year = year(date),
    month = month(date),
    decade = floor(year/10) * 10,
    single = year - decade,
    decade = paste0(decade, "s")
  ) %>% 
  ggplot(aes(month, uempmed)) +
  geom_point() +
  facet_grid(decade ~ single)

enter image description here

My question is, how can I get ride of the first 7 panels (and the last 4), leaving them totally blank?


Solution

  • I have found this easiest to do by editing the panel grobs in a gtable before plotting.

    First lets save the ggplot object in myplot

    myplot <- economics %>%
      filter(date >= ymd(19680101)) %>% 
      mutate(
        year = year(date),
        month = month(date),
        decade = floor(year/10) * 10,
        single = year - decade,
        decade = paste0(decade, "s")
      ) %>% 
      ggplot(aes(month, uempmed)) +
      geom_point() +
      facet_grid(decade ~ single)
    

    Now we can remove the panels before plotting. I demonstrate using cowplot::plot_to_gtable, although there are also several other packages that provide functions to convert a ggplot into a gtable.

    library(cowplot)
    library(grid)
    gt <- plot_to_gtable(myplot)
    to.delete = which (gt$layout$t == 8 & gt$layout$r <= 19 & grepl('panel', gt$layout$name))
    to.delete = c(to.delete, which(gt$layout$t == 18 & gt$layout$r >= 17 & grepl('panel', gt$layout$name)))
    
    gt$grobs[to.delete] <- NULL
    gt$layout <- gt$layout[-to.delete, ]
    grid.newpage()
    grid.draw(gt)
    

    enter image description here

    We can also move up the axes for the empty cells like this:

    to.move = which(gt$layout$r >= 17 & grepl('axis-b', gt$layout$name))
    gt$layout$t[to.move] <- gt$layout$t[to.move] - 2
    gt$layout$b[to.move] <- gt$layout$b[to.move] - 2
    grid.newpage()
    grid.draw(gt)
    

    enter image description here