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, `)
2
  • I'm using R version 4.1.1 and ggplot2_3.3.5 Commented Oct 13, 2021 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 dplyr.tidyverse.org/articles/programming.html. Commented Oct 13, 2021 at 19:44

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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, `)

Comments

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, ")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.