Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2, how do you use access dataframe elements from within the function?

Tags:

r

ggplot2

I'm trying to create plots in with ggplot2 to standardize the creation of many similar plots. Given you can stack numerous options, using theme(), stat_*(), or geom_*() with the + operator, how can you wrap this inside a function?

I'd like to create a function to plot sections of a data frame, for example :

library(ggplot2)
test<-function(fdata,fx){
  p<-ggplot(fdata,aes(x=fx,y=mpg))+geom_point()
  print(p)}; 
test(mtcars,wt)

returns an error of:

Error in eval(expr, envir, enclos) : object 'fx' not found

but changing the aesthetic definition to a locally scoped variable (e.g. x=fx to x=wt) works, but won't use the function's second option of 'fx':

library(ggplot2)
test<-function(fdata,fx){
  p<-ggplot(fdata,aes(x=wt,y=mpg))+geom_point()
  print(p)}; 
test(mtcars,wt)

How do I write a function to create a plot from different variables in a data frame?

E.g. how do I write function test so that I could call multiple times to get similar plots, like :

test(mtcars,'wt')  #scatter plot of wt x mpg
test(mtcars,'disp') #scatter plot of disp x mpg
test(mtcars,'hp')  #scatter plot of hp x mpg
like image 625
user2387353 Avatar asked Nov 29 '25 15:11

user2387353


1 Answers

The trick here is to use aes_string instead of using aes. The former allows you to pass strings as aesthetics. This allows you to pass a variable containing the string of the aesthetic, e.g. 'wt' in case of plotting mtcars. You need to modify your code like this:

library(ggplot2)
test <- function(fdata, fx) {
  p <- ggplot(fdata, aes_string(x = fx, y = "mpg")) + geom_point()
  print(p)
}
test(mtcars, "wt")
like image 191
Paul Hiemstra Avatar answered Dec 02 '25 06:12

Paul Hiemstra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!