0

I am trying to write a function in ggplot2 and obtain this error message:

Error in layout_base(data, 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
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
user34771
  • 455
  • 1
  • 4
  • 15

1 Answers1

0

Here is reproducible solution where your x, y, and fac arguments must be passed as character:

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)

enter image description here

Thanks to commenters @Roland and @aosmith for pointing the way to this solution.

Community
  • 1
  • 1
bdemarest
  • 14,397
  • 3
  • 53
  • 56