2

I have a function that when I choose the variables it plots me a ggplot.

It works well.

gg_f <- function(df, var_x){

  ggplot(df, aes(x = {{var_x}}, mpg)) + geom_point()

}

gg_f(df = mtcars, var_x = cyl)

But when I tried to set the plot title as the var_x variable that I choose I have problems.

I tried o use glue but it didnt work:

gg_f <- function(df, var_x){
    
    ggplot(mtcars, aes(x = {{var_x}}, mpg)) + geom_point() + labs(title = glue::glue({var_x})
    
}

How can I do this?

1

1 Answer 1

3

You can use substitute(var_x)

library(ggplot2)

gg_f <- function(df, var_x){

  ggplot(df, aes(x = {{var_x}}, mpg)) + 
    geom_point() +
    labs(title = substitute(var_x))

}

gg_f(df = mtcars, var_x = cyl)

Or rlang::englue:

library(ggplot2)

gg_f <- function(df, var_x){

  ggplot(df, aes(x = {{var_x}}, mpg)) + 
    geom_point() +
    labs(title = rlang::englue("{{var_x}}"))

}

gg_f(df = mtcars, var_x = cyl)

Created on 2022-04-10 by the reprex package (v2.0.1)

Sign up to request clarification or add additional context in comments.

7 Comments

I suppose the rlang version is labs(title = as_name(enquo(var_x))).
@Axeman or rlang::englue
@AllanCameron if I want to use "outside" my function? Something like: gg_f(df = mtcars, var_x = cyl) + labs(......)
@Laura why wouldn't you just put labs(title = "cyl") if it was outside your function?
@Laura but if you put 'labs()` outside your function, you have no way to pass arguments to it other than specifying them directly.
|

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.