Reputation: 1
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, `)
Upvotes: 0
Views: 1024
Reputation: 389047
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, ")
PS - Not sure why you have such complex name for the column instead of standard one.
Upvotes: 1
Reputation: 638
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, `)
Upvotes: 1
Reputation: 3412
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, ")
Upvotes: 0