'In ggplot, how to set plot title as x variable choosed when using a function
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?
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
