ggplot2 icon indicating copy to clipboard operation
ggplot2 copied to clipboard

Provide some tidyselect like interface for facetting

Open hadley opened this issue 3 years ago • 2 comments

So you could do (e.g.)

diamonds |>
  ggplot() |>
  geom_histogram(aes(carat)) |>
  facet_wrap(vars_select(starts_with("c") & !carat))

(Motivating real function: https://twitter.com/avakiai/status/1574392928545513472)

I don't think this is that useful in direct analysis but it makes certain programmatic usages possible that are otherwise very hard.

Alternatively if it was possible to make facet_wrap(vars(data.frame(vs, cyl)) work, then we could attack the problem via across()/pick() which has the advantage of working the same way as in dplyr.

hadley avatar Sep 26 '22 13:09 hadley

I'm pretty sure we can make facet_wrap(vars(data.frame(vs, cyl)) work, but I'm unsure how this will solve the issue in the tweet. If we want to pass strings as facetting variables, there are options like data_syms().

library(ggplot2)

hist_plot <- function(df, x, facets) {
  df |> 
    ggplot() +
    geom_histogram(aes({{ x }})) +
    facet_wrap(vars(!!!rlang::data_syms(facets)))
}

mpg |> hist_plot(displ, facets = c("year", "cyl"))
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Created on 2024-12-09 with reprex v2.1.1

teunbrand avatar Dec 09 '24 15:12 teunbrand

The above should also work if you derive the facet names via some tidyselect magic.

library(ggplot2)
library(tidyselect)

hist_plot <- function(df, x, select) {
  select <- names(tidyselect::eval_select(enexpr(select), df))
  df |> 
    ggplot() +
    geom_histogram(aes({{ x }})) +
    facet_wrap(vars(!!!rlang::data_syms(select)))
}

mpg |> hist_plot(displ, select = where(~ length(unique(.x)) < 4))
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Created on 2024-12-09 with reprex v2.1.1

teunbrand avatar Dec 09 '24 15:12 teunbrand