2

Here are some workarounds for the issue, but is there a reason why you can pass a string for rows in the ggplot2::facet_grid() but not for cols?

This works (notice the rows attribute):

f_varname <- 'drv'

ggplot( mpg, aes( displ, cty ) ) + geom_point() +

    facet_grid( rows = f_varname )

But this does not (notice the cols attribute):

f_varname <- 'drv'

ggplot( mpg, aes( displ, cty ) ) + geom_point() +

    facet_grid( cols = f_varname )

# => Error: `cols` must be `NULL` or a `vars()` specification

Instead, you have to use the vars() specification for the cols:

ggplot( mpg, aes( displ, cty ) ) + geom_point() +
    
    facet_grid( cols = vars( drv ) )

which can not handle a string:

f_varname <- 'drv'

ggplot( mpg, aes( displ, cty ) ) + geom_point() +
    
    facet_grid( cols = vars( f_varname ) )

# =>
# Error: At least one layer must contain all faceting variables: `f_varname`.
# * Plot is missing `f_varname`
# * Layer 1 is missing `f_varname`

From the linked discussion, this answer also works with the string:

f_varname <- 'drv'

ggplot( mpg, aes( displ, cty ) ) + geom_point() +
    
    facet_grid( reformulate( f_varname ) )
2
  • 2
    From the online doc, it looks like this is a legacy feature: "For compatibility with the classic interface, rows can also be a formula...". I'm guessing the character variable containing the name of the column can be coerced to an appropriate formula. Commented Jun 15, 2021 at 9:26
  • Thanks @Limey. Sounds like a possible explanation. These kind of features always keep me always with R, though. Commented Jun 15, 2021 at 17:40

1 Answer 1

2

I think @Limey's explanation in the comments is the answer to your question, but if you're looking for a practical solution (outside of those you've linked) you can turn the string into a symbol (using sym()) then pass it to vars with the bang-bang operator, e.g.

library(tidyverse)
f_varname <- sym("cyl")
ggplot(mpg, aes(displ, cty)) +
  geom_point() +
  facet_grid(cols = vars(!!f_varname))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @jared_mamrot. Although I really don't understand the Bang Bang operator (nor data masking, TBH), your solution seems a more robust solution than the one using reformulate()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.