Home > OS >  programming with ggplot using aes_ or aes_string with special characters in column names
programming with ggplot using aes_ or aes_string with special characters in column names

Time:10-14

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

CodePudding user response:

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

CodePudding user response:

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