Search code examples
rggplot2facetfacet-grid

Using facet tags and strip labels together in ggplot2


I'd like to create a figure using ggplot2's facet_grid, like below:

# Load ggplot2 library for plotting
library(ggplot2)

# Plot dummy data
p <- ggplot(mtcars, aes(mpg, wt)) 
p <- p + geom_point() 
p <- p + facet_grid(gear ~ cyl)
print(p)

This is great, but since it's going in a journal article each panel also needs to be labelled with a, b, c, etc. The package egg has a great function for this called tag_facet, which is used as follows:

# Load egg library for tagging
library(egg)
#> Warning: package 'egg' was built under R version 3.5.3
#> Loading required package: gridExtra

# Same plot but with tags for each facet
p <- ggplot(mtcars, aes(mpg, wt)) 
p <- p + geom_point() 
p <- p + facet_grid(gear ~ cyl)
tag_facet(p)

Created on 2019-05-09 by the reprex package (v0.2.1)

As required, I now how letter labels on each panel. But, as you can see, my strip labels have disappeared!

My question: How do I retain my strip labels, whilst also adding tags?


Solution

  • Of course, I find a solution immediately after asking. The problem appears to be that tag_facet sets strip labels to element_blank, which can be fixed by calling theme after calling tag_facet.

    # Load libraries
    library(ggplot2)
    library(egg)
    #> Warning: package 'egg' was built under R version 3.5.3
    #> Loading required package: gridExtra
    
    # Create plot
    p <- ggplot(mtcars, aes(mpg, wt)) 
    p <- p + geom_point() 
    p <- p + facet_grid(gear ~ cyl)
    p <- tag_facet(p)
    p <- p + theme(strip.text = element_text())
    print(p)
    

    Created on 2019-05-09 by the reprex package (v0.2.1)