Search code examples
rggplot2facet-grid

How to format grid title and entries in ggplot2::facet_grid


I have a plot using facet_grid() and would like to modify the facet grid's entries.

Consider the following MWE:

library(ggplot2)
ggplot(mpg, aes(displ, cty, fill=cyl)) + 
  geom_point() +
  scale_fill_continuous() +
  facet_grid(rows = vars(drv))

I would like to replace the entries 4, f, and r on the right hand side of each row with characters (e.g. c("Case 1", "Case 2", "Case 3") and add a title box right of the entries (i.e. between the grey box and the legend (cyl).

The documentation for facet_grid hasn't helped me - can someone point me to the right direction?


Solution

  • You would have to provide a labelling function to the labeller argument in facet_grid(), which uses a named character vector as lookup table.

    library(ggplot2)
    ggplot(mpg, aes(displ, cty, fill=cyl)) + 
      geom_point() +
      scale_fill_continuous() +
      facet_grid(rows = vars(drv),
                 labeller = as_labeller(c("4" = "Case1", "f" = "Case2", "r" = "Case3")))
    

    Created on 2020-05-28 by the reprex package (v0.3.0)

    EDIT:

    To use an extra strip layer as a spanning title, you could use facet_nested() from ggh4x (full disclaimer: I build that package).

    library(ggplot2)
    library(ggh4x)
    
    ggplot(mpg, aes(displ, cty, fill=cyl)) + 
      geom_point() +
      scale_fill_continuous() +
      facet_nested(rows = vars("title", drv),
                 labeller = as_labeller(c("4" = "Case1", "f" = "Case2", 
                                          "r" = "Case3", "title" = "My Title Here")))
    

    Created on 2020-05-28 by the reprex package (v0.3.0)

    If you don't particularly care about the strip being there, you could use a secondary y-axis guide.

    library(ggplot2)
    ggplot(mpg, aes(displ, cty, fill=cyl)) + 
      geom_point() +
      scale_fill_continuous() +
      facet_grid(rows = vars(drv),
                 labeller = as_labeller(c("4" = "Case1", "f" = "Case2", "r" = "Case3"))) +
      guides(y.sec = guide_none("My Title Here"))
    

    Created on 2020-05-28 by the reprex package (v0.3.0)