ggplot2: How to dynamically specify faceting variable?

50 Views Asked by At

Let's say I have a dataframe with a column facet that I want to use for faceting. Easy:

ggplot(...) + facet_grid(. ~ facet)

But I want to dynamically specify the faceting column like so:

FACET_COLUMN <- 'facet'
ggplot(...) + facet_grid(. ~ FACET_COLUMN) # of course doesn't work

How does that work? I'm basically looking for a faceting equivalent to aes_string().

2

There are 2 best solutions below

1
benson23 On BEST ANSWER

You can get the variable in facet_grid.

Using the built-in diamonds dataset as example:

library(ggplot2)

FACET_COLUMN <- "color"

ggplot(diamonds, aes(x, y)) +
  geom_point() +
  facet_grid(. ~ get(FACET_COLUMN))

0
teunbrand On

The recommended approach by the vignette is to use the .data pronoun.

library(ggplot2)

FACET_COLUMN <- "cyl"

ggplot(mtcars, aes(disp, mpg)) +
  geom_point() +
  facet_wrap(vars(.data[[FACET_COLUMN]]))

Created on 2024-02-07 with reprex v2.1.0