Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curly Curly on ggplot label

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)
like image 923
Vaibhav Singh Avatar asked Sep 16 '25 02:09

Vaibhav Singh


2 Answers

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, .))
like image 191
Ronak Shah Avatar answered Sep 18 '25 17:09

Ronak Shah


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)

like image 27
teunbrand Avatar answered Sep 18 '25 16:09

teunbrand