简体   繁体   English

尝试在ggplot2中编写绘图函数时出错

[英]Error in trying to write a plotting function in ggplot2

I am trying to write a function in ggplot2 and obtain this error message: 我试图在ggplot2中编写一个函数并获取此错误消息:

Error in layout_base(data, vars, drop = drop) : layout_base中的错误(数据,vars,drop = drop):
At least one layer must contain all variables used for facetting 至少一层必须包含用于构面的所有变量

Here is my code: 这是我的代码:

growth.plot<-function(data,x,y,fac){ 
gp <- ggplot(data = data,aes(x = x, y = y)) 
gp <- gp + geom_point()  + facet_wrap(~ fac)
return(gp)
}

growth.plot(data=mydata, x=x.var, y=y.var,fac= fac.var)

If I try without the function, the plot appears perfectly 如果我尝试不使用该功能,该图将完美显示

gp1 <- ggplot(data = mydata,aes(x = x.var), y = y.var))
gp1+ geom_point()+ facet_wrap(~ fac.var) # this works

Here is reproducible solution where your x, y, and fac arguments must be passed as character: 这是可重现的解决方案,其中x,y和fac参数必须作为字符传递:

library(ggplot2)

make_plot = function(data, x, y, fac) {
    p = ggplot(data, aes_string(x=x, y=y, colour=fac)) +
        geom_point(size=3) +
        facet_wrap(as.formula(paste("~", fac)))
    return(p)
}

p = make_plot(iris, x="Sepal.Length", y="Petal.Length", fac="Species")

ggsave("iris_plot.png", plot=p, height=4, width=8, dpi=120)

在此处输入图片说明

Thanks to commenters @Roland and @aosmith for pointing the way to this solution. 感谢评论者@Roland和@aosmith指出了该解决方案的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM