ggplot aes_string with interaction

六眼飞鱼酱① 提交于 2019-12-01 15:03:26

问题


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?


回答1:


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()


来源:https://stackoverflow.com/questions/15502263/ggplot-aes-string-with-interaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!