I have an issue trying to create a function to creat a plot using ggplot. Here is some code:
y1<- sample(1:30,45,replace = T)
x1 <- rep(rep(c("a1","a2","a3","a4","a5"),3),each=3)
x2 <- rep(rep(c("b1","b2","b3","b4","b5"),3),each=3)
df <- data.frame(y1,x1,x2)
library(Rmisc)
dfsum <- summarySE(data=df, measurevar="y1",groupvars=c("x1","x2"))
myplot <- function(d,v, w,g) {
pd <- position_dodge(.1)
localenv <- environment()
ggplot(data=d, aes(x=v,y=w,group=g),environment = localenv) +
geom_errorbar(data=d,aes(ymin=d$w-d$se, ymax=d$w+d$se,col=d$g), width=.4, position=pd,environment = localenv) +
geom_line(position=pd,linetype="dotted") +
geom_point(data=d,position=pd,aes(col=g))
}
myplot(dfsum,x1,y1,x2)
As I was looking for similar questions, I found that specifying the local environment should solve the issue. However it did not help in my case.
Thank you
Preliminary Note
When looking at your
data.frame
, thegroup
variable does not make any sense, as it is perfectly confounded with the x variable. Hence I adapted your data a bit, to show a full example:Data
Plot Function
Explanation
Your problem occurs because the scope of
x1
x2
andy1
was ambiguous. As you defined these variables also at the top environmnet,R
did not complain in the first place. If you had added arm(x1, x2, y1)
in your original code right after you created yourdata.frame
you would have seen the problem already eralier.ggplot
looks in thedata.frame
you provide for all the variables you want to map to certain aesthetics. If you want to create a function, where you specify the name of the aesthatics as arguments, you should useaes_string
instead ofaes
, as the former expects a string giving the name of the variable rather than the variable itself.With this approach however, you cannot do calculations on the spot, so you need to create the variables
ymin
andymax
beforehand in yourdata.frame
. Furthermore, you do not need to provide the data argument for each geom if it is the same as provided toggplot
.