Skip to content

Programming with facets #5181

@hadley

Description

@hadley

Extracted from R4DS because we're trying to get down to a page limit. I think this would be good content for https://ggplot2.tidyverse.org/articles/ggplot2-in-packages.html


Faceting

Unfortunately, programming with faceting is a special challenge, because faceting was implemented before we understood what tidy evaluation was and how it should work.
So you have to learn a new syntax.
When programming with facets, instead of writing ~ x, you need to write vars(x) and instead of ~ x + y you need to write vars(x, y).
The only advantage of this syntax is that vars() uses tidy evaluation so you can embrace within it:

# https://twitter.com/sharoz/status/1574376332821204999
foo <- function(x) {
  ggplot(mtcars, aes(x = mpg, y = disp)) +
    geom_point() +
    facet_wrap(vars({{ x }}))
}

foo(cyl)

As with data frame functions, it can be useful to make your plotting functions tightly coupled to a specific dataset, or even a specific variable.
For example, the following function makes it particularly easy to interactively explore the conditional distribution of carat from the diamonds dataset.

#| fig.show: hide

# https://twitter.com/yutannihilat_en/status/1574387230025875457
density <- function(color, facets, binwidth = 0.1) {
  diamonds |> 
    ggplot(aes(x = carat, y = after_stat(density), color = {{ color }})) +
    geom_freqpoly(binwidth = binwidth) +
    facet_wrap(vars({{ facets }}))
}

density()
density(cut)
density(cut, clarity)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions