Now with curly-curly, what do we do about quo_text?

Now that curly-curly has been introduced, what's the approach for using quo_text? Consider:

corr_plot_old <- function(df, x, y, title = NULL) {
  x_quo <- enquo(x)
  y_quo <- enquo(y)
  
  ggplot(df, aes(x = !!x_quo, y = !!y_quo)) +
    geom_point(size = 2, alpha = 0.8) +
    geom_smooth(method = "lm", se = FALSE) +
    labs(
      title = title,
      subtitle = paste(rlang::quo_text(x_quo), "vs.", rlang::quo_text(y_quo))
    )
}

corr_plot_old(mtcars, mpg, hp)

My attempt to update this fails because quo_text wants a quosure not a bare object. Can I have my cake and eat it too?

corr_plot_new <- function(df, x, y, title = NULL) {
  ggplot(df, aes(x = {{ x }}, y = {{ y }})) +
    geom_point(size = 2, alpha = 0.8) +
    geom_smooth(method = "lm", se = FALSE) +
    labs(
      title = title,
      subtitle = paste(rlang::quo_text(x), "vs.", rlang::quo_text(y))
    )
}

# FAILS...
corr_plot_new(mtcars, mpg, hp)

I've tried a few things like rlang::as_string(), but at this point, I'm just guessing. What's the path forward on this? Or do I still need to use enquo()?

1 Like

If you need to inspect or modify the expression in any way, which is the case in your example, you still need to capture it with enquo() or enquos().

By the way, I recommend using as_label() instead of quo_text() for your application. The latter might return a multi-line string while the former always returns a single-line string, which is suitable for creating axes labels.

3 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.