Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing parameters to ggplot

Tags:

would like to create a function that generates graphs using ggplot. For the sake of simplicity, the typical graph may be

ggplot(car, aes(x=speed, y=dist)) + geom_point()  

The function I would like to create is of the type

f <- function(DS, x, y) ggplot(DS, aes(x=x, y=y)) + geom_point() 

This however won't work, since x and y are not strings. This problem has been noted in previous SO questions (e.g., this one), but without providing, in my view, a satisfactory answer. How would one modify the function above to make it work with arbitrary data frames?

like image 406
gappy Avatar asked Jun 27 '11 04:06

gappy


1 Answers

One solution would be to pass x and y as string names of columns in data frame DS.

f <- function(DS, x, y) {       ggplot(DS, aes_string(x = x, y = y)) + geom_point()   } 

And then call the function as:

f(cars, "speed", "dist") 

However, it seems that you don't want that? Can you provide an example why you would need different functionality? Is it because you don't want to have the arguments in the same data frame?

like image 113
Grega Kešpret Avatar answered Oct 17 '22 06:10

Grega Kešpret