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
3
  • 4
    Have a look at aes_string. Commented Oct 2, 2014 at 9:45
  • Thank you, I tried but unfortunatelly it does not work. Commented Oct 2, 2014 at 16:25
  • I think this answer may be what you are looking for. Commented Oct 2, 2014 at 16:55

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, it works perfectly. Never easy to find its way through the small R subtleties.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.