Curly Curly on ggplot label

Viewed 133

I am using curly curly using in labs in ggplot, it doesn't seem to work, how to use the label on the labs in ggplot in Try #2. For Try#3 I want to pass all numeric variable through purr in the function.

TRY #1 - This works

library(tidyverse)

myplot <- function(df,col) {
  df %>% 
  ggplot(aes(x={{col}}))+
  geom_histogram()+
   # labs(title=paste0("Histogram for ",{{col}}))+
    theme_classic()
}

myplot(iris,Sepal.Length)

TRY #2 - This doesnt work

myplot <- function(df,col) {
  df %>% 
  ggplot(aes(x={{col}}))+
  geom_histogram()+
   labs(title=paste0("Histogram for ",{{col}}))+
    theme_classic()
}

myplot(iris,Sepal.Length)

TRY #3 - This doesnt work either

myplot <- function(df,col) {
  df %>% 
  ggplot(aes(x={{col}}))+
  geom_histogram()+
  theme_classic()
}

iris[,-5] %>% 
  map(myplot)
3 Answers

You can do old-school deparse(substitute(...)) to capture the symbol as text.

library(tidyverse)

myplot <- function(df,col) {
  df %>% 
    ggplot(aes(x={{col}}))+
    geom_histogram()+
    labs(title=paste0("Histogram for ", deparse(substitute(col))))+
    theme_classic()
}

myplot(iris,Sepal.Length)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Created on 2021-08-20 by the reprex package (v1.0.0)

If you are ok passing column names as strings.

library(ggplot2)
library(purrr)

myplot <- function(df,col) {
  df %>% 
    ggplot(aes(x=.data[[col]]))+
    geom_histogram()+
    labs(title=paste0("Histogram for ",col))+
    theme_classic()
}

list_plot <- map(names(iris)[-5], ~myplot(iris, .))

Another option would be to make use of rlang::as_label(rlang::enquo(col)):

library(ggplot2)

myplot <- function(df, col) {
  ggplot(df, aes(x={{col}}))+
    geom_histogram()+
    labs(title=paste0("Histogram for ", rlang::as_label(rlang::enquo(col)))) +
    theme_classic()
}

myplot(iris,Sepal.Length)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

If you want to loop over multiple columns one option would be to rewrite your function slightly to make use of the .data pronoun from rlang and to loop over the column names:

myplot2 <- function(df, col) {
  ggplot(df, aes(x = .data[[col]]))+
    geom_histogram()+
    labs(title=paste0("Histogram for ", col)) +
    theme_classic()
}

p <- purrr::map(names(iris[,-5]), myplot2, df = iris)

p[[2]]
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Related