Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot aes_string with interaction

Using aes_string makes it easy to construct functions to take parameters to plot:

p <- ggplot(mtcars, aes_string(x="mpg", y="wt", group=interaction("cyl","gear"))) + 
     geom_point()

Now to write the the function

make_plot <- function(x,y, interact) {
    p <- ggplot(mtcars, aes_string(x=x, y=y, group=interact)) + 
         geom_point()
}

and to call the function

make_plot("mpg","wt",c("cyl","gear"))

But here the interaction is not used, i.e., it is not interpreted. I don't want to use separate variables for interaction bcos the same function could be used for other plots. How should I go about making the interaction variable such that it is accepted and understood by ggplot?

like image 667
knk Avatar asked Mar 19 '13 14:03

knk


1 Answers

According to this answer this should work (without quoting the colnames):

p <- ggplot(mtcars, aes_string(x=x, y=y, group=paste0("interaction(", paste0(interact, 
    collapse =  ", "), ")"))) + geom_point()
like image 91
SaschaH Avatar answered Oct 27 '22 16:10

SaschaH