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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With