4

I'm trying to create a line graph and keep getting an error when I add in the error bars (just getting started with R, so apologies!). I'm not sure why - help would be appreciated!

Group = c("a","a","b","b","a","a","b","b")
Time = c(1,2,1,2,1,2,1,2)
Code = c("A","A","A","A","B","B","B","B")
Mean = (2,6,7,5,6,1,2,8)
SE = c(1.9,1.7,1.5,1.3,2,1.8,2.3,1.5)
dataset=data.frame(Group,Time,Code,Mean,SE)

ggplot(data=dataset) + geom_line(aes(x=Time,y=Mean,colour=Code,linetype=Group))+ 
  scale_x_continuous(breaks=c(1,2)) + 
  scale_linetype_manual(values=c(2,1)) + 
  geom_point(aes(x=Time,y=Mean,colour=Code,linetype=Group)) + 
  geom_errorbar(aes(ymin=Mean-SE,ymax=Mean+SE),width=.1,position=dodge)

The problem has to do with the last line -- code works fine without it. But with it, I get: Error in eval(expr, envir, enclos) : object 'x' not found.

So what am I doing wrong with the geom_errorbar line?

1 Answer 1

5

The first thing I would try is to define the aesthetics only once and do so in the ggplot() function. Ie.

ggplot(data=dataset,aes(x=Time,y=Mean,colour=Code,linetype=Group,ymin=Mean-SE,ymax=Mean+SE)) + 
geom_line() + 
scale_x_continuous(breaks=c(1,2)) + 
scale_linetype_manual(values=c(2,1)) + 
geom_point() + 
geom_errorbar(width=.1,position='dodge')

This is because ggplot doesn't guarantee to pass all of the variables that are in the original dataset and weird results can result from depending on this.

Edit: I just noticed that x never gets defined for geom_errorbar, adding x=Time to either the aes of ggplot() or geom_errorbar() should fix the problem. However, doing the latter is really not recommended.

If you give example data (eg. dput) I would be able to help you further.

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

3 Comments

Yes -- I should have given some data: -- added above
Ach! -- that's it -- missing x. I'll try defining aes after ggplot. I think I'd tried that before and it was not working for me for some reason. Still, your suggestion makes sense! Many thanks!
My pleasure. I tried my code and it works for me now (I had to add quotes to 'dodge').

Your Answer

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