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?
CodePudding user response:
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)