Search code examples
rggplot2cowplot

Arrange faceted plots in a grid - how to completely remove facet labels to avoid overlapping


I am a bit stuck with the following: I want to arrange multiple (gg)plots into a grid with cowplot::plot_grid. Below is an example with two ggplots (g_bottom and g_top), both faceted. The bottom one has the facet labels deleted as they are redundant. However, there seems to remain the contour of the background or so, acting as cutting with a white line the top plot (see image below).

How could I fix this?

What have I tried so far:

Instead of strip.background = element_blank() I also tried strip.background = element_rect(fill = NA, color = NA) in theme, but with no success.

If I set rect = element_blank(), it somehow works, but I lose the entire plot border. I was then hopping that rect = element_rect(fill = "transparent", colour = NA) would do it, but still no success. I also just tried colour = NULL or colour = "transparent" also with no success.

library(ggplot2)
library(cowplot)

g <- ggplot(mpg, aes(class)) + 
    geom_bar() + 
    facet_grid(. ~ year) +
    theme_bw()

g_bottom <- g +
    theme(
        strip.text = element_blank(),
        strip.background = element_blank(), 
        # strip.background = element_rect(fill = NA, color = NA) # didn't work either
        # Was hoping that this will do the trick, bot no success:
        rect = element_rect(fill = "transparent", color = NA)
    )

g_top <- g +
    labs(x = element_blank()) +
    theme(
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank()
    )

plot_grid(g_top, NULL, g_bottom, 
          # used NULL to be able to tweak spacing between plots with rel_heights
          align = "hv",
          nrow = 3,
          rel_heights = c(1, -0.2, 1))

enter image description here I could go around the problem by not faceting and creating each of the 4 plots individually, but maybe there is a more straightforward solution with some theme argument which I'm too blinded to see any-further...


Solution

  • Eventually, using rect = element_blank() in theme when making g_bottom and then adding panel.border = element_rect(colour = "black") seems to do the trick. I still fail to understand why the initial trials didn't work as expected.

    library(ggplot2)
    library(cowplot)
    
    g <- ggplot(mpg, aes(class)) + 
        geom_bar() + 
        facet_grid(. ~ year) +
        theme_bw()
    
    g_bottom <- g +
        theme(
            strip.text = element_blank(),
            rect = element_blank(),
            panel.border = element_rect(colour = "black")
        )
    
    g_top <- g +
        labs(x = element_blank()) +
        theme(
            axis.text.x = element_blank(),
            axis.ticks.x = element_blank()
        )
    
    plot_grid(g_top, NULL, g_bottom + theme(panel.border = element_rect(colour = "black")),
              align = "hv",
              nrow = 3,
              rel_heights = c(1, -0.2, 1))