Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass character strings to ggplot2 within a function

Tags:

string

r

ggplot2

Often I use ggplot2 in my work and build wrapper functions to speed up my work flow. The use of the non-standard evaluation (NSE) aes forces me to use the actual variable names rather than passing character strings. So I copy and rename dataframes and variable names to appease ggplot2. There's got to be a better way. How can I make ggplot2 accept unknown dataframes and column names via a function wrapper without replicating the dataframe and using generic column names?

This works:

ggplot(mtcars, aes(x=mpg, y=hp)) +     geom_point() 

This does not:

FUN <- function(dat, x, y) {     ggplot(dat, aes(x = x, y = y)) +         geom_point() }  FUN(mtcars, "mpg", "hp") 
like image 520
Tyler Rinker Avatar asked Nov 07 '13 01:11

Tyler Rinker


2 Answers

There's the aes_string function, that I don't really see given prominence, which does exactly this:

FUN <- function(dat, x, y) {     ggplot(dat, aes_string(x = x, y = y)) +         geom_point() }  FUN(mtcars, "mpg", "hp") 
like image 68
Tyler Rinker Avatar answered Sep 24 '22 06:09

Tyler Rinker


It is now recommended to use .data pronoun

FUN <- function(dat, x, y) {   ggplot(dat, aes(x = .data[[x]], y = .data[[y]])) +     geom_point() }  FUN(mtcars, "mpg", "hp") 

enter image description here

Couple of other alternatives -

#Using get FUN <- function(dat, x, y) {   ggplot(dat, aes(x = get(x), y = get(y))) +     geom_point() }  #Using sym  FUN <- function(dat, x, y) {   ggplot(dat, aes(x = !!sym(x), y = !!sym(y))) +     geom_point() } 
like image 20
Ronak Shah Avatar answered Sep 24 '22 06:09

Ronak Shah