0

I need to run ggplot in a function. The input data.frame/tibble passed to the function has special characters (white spaces, commas etc.) in the columns with data to be plotted. The column names to be plotted are passed as arguments to the function. Here is a working example, both aes_ and aes_string fail, but for different reasons. Help appreciated

trial.tbl_df <- tibble(a = 1:3, `complex, `=4:6)

plotfunc <- function(tbl2plot,yvar){

  ggplot(tbl2plot,aes_(x = "a", y = yvar )) + 
    geom_point()

}

plotfunc(tbl2plot = trial.tbl_df, yvar = `complex, `)
stefan
  • 90,330
  • 6
  • 25
  • 51
jmf11
  • 1
  • I'm using R version 4.1.1 and ggplot2_3.3.5 – jmf11 Oct 13 '21 at 19:39
  • 2
    Note that `aes_` and `aes_string` are both soft-deprecated in `ggplot2`, I suggest you look into programmatic quasi-quotation methods. Look for tutorials on "tidy evaluation", such as https://dplyr.tidyverse.org/articles/programming.html. – r2evans Oct 13 '21 at 19:44

3 Answers3

1

As @r2evans mentioned, you can use tidy evaluation as aes_ and aes_string are deprecated:

trial.tbl_df <- tibble(a = 1:3, `complex, `=4:6)


plotfunc <- function(data, y){
  
  y <- enquo(y)

  ggplot(data, aes(x = a, y = !!y)) + 
    geom_point()
  
}

plotfunc(data = trial.tbl_df,  y = `complex, `)

danh
  • 618
  • 3
  • 7
1

aes_ and aes_string both are used when you pass column names as string. Since both of them are deprecated you can use .data.

library(ggplot2)

trial.tbl_df <- tibble::tibble(a = 1:3, `complex, `=4:6)

plotfunc <- function(tbl2plot,yvar){
  
  ggplot(tbl2plot,aes(x = a, y = .data[[yvar]])) + 
    geom_point()
  
}

plotfunc(tbl2plot = trial.tbl_df, yvar = "complex, ")

enter image description here

PS - Not sure why you have such complex name for the column instead of standard one.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

How about using aes_ and as.name:

trial.tbl_df <- tibble(a = 1:3, `complex, `=4:6)

plotfunc <- function(tbl2plot,yvar){
  
  ggplot(tbl2plot ,aes_(x = ~a, y = as.name(yvar))) + 
    geom_point()
  
}

plotfunc(tbl2plot = trial.tbl_df, yvar = "complex, ")
SmokeyShakers
  • 3,372
  • 1
  • 7
  • 18