Ivo
Ivo

Reputation: 4200

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?

Upvotes: 1

Views: 1136

Answers (2)

teunbrand
teunbrand

Reputation: 38063

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)

Upvotes: 2

KoenV
KoenV

Reputation: 4283

You could also consider adding a mutated column to your data, like in the following:

library(dplyr)
mpg_2 <- mpg %>%
  mutate(drv_2 = case_when(
    drv == "4" ~ "Case1",
    drv == "f" ~ "Case2",
    drv == "r" ~ "Case3" 
  ))

ggplot(mpg_2, aes(displ, cty, fill=cyl)) + 
  geom_point() +
  scale_fill_continuous() +
  facet_grid(rows = vars(drv_2))

Upvotes: 1

Related Questions