rggplot2facetfacet-grid

ggplot2: How to dynamically specify faceting variable?


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().


Solution

  • 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))