Lost in transcription Lost in transcription - 1 month ago 19
R Question

Adding error bars to ggplot2

I have made a graph using ggplot from data I transformed into means with code:

means<-ddply(shlf, .(Location), summarize, sal=mean(sal),temp=mean(temp), Calanus=mean(Calanus), Triconia=mean(Triconia))

means
Location sal temp Calanus Triconia
1 bank_A 29.59429 7.642857 2217.971 20.417143
2 bank_B 29.20786 6.334286 1199.756 7.016429
3 bank_C 32.00357 7.000714 1504.554 37.397857
4 shelf_slope 35.07786 8.417143 5978.366 459.752857
5 shore_near 29.51643 7.053571 1412.179 49.303571
6 trough 34.46571 7.912143 2928.862 381.235714


and made the graph using this code:

p1<-ggplot(means, aes(x = temp, y =Triconia , group = Location, color = Location)) +
geom_line() +
geom_point(size = 5.0) +
ggtitle("Number of Triconia at different locations showing temp.") + ylab("Triconia (indv.)")+xlab("Temp. (Celsius)")+
theme_hc(bgcolor = "darkunica") +
scale_fill_hc("darkunica")


I would like to know if there is anyway I can add error bars to this graph. I know I have to transform the data to have more summaries but not sure how to proceed. Tried to do it seperately for each column but could'nt make a graph from it. like this:

Temperature <- ddply(shlf, c("Location"), summarise,
N = length(temp),
mean.temp = mean(temp),
sd = sd(temp),
se = sd / sqrt(N))


Any help is appreciated.

Answer

You are almost there. This is based on se as provided in Temperature data:

means$upper = Temperature$mean.temp + Temperature$se
means$lower = Temperature$mean.temp - Temperature$se

ggplot(means, aes(x = temp,
                  y = Triconia,
                  color = Location)) +
   geom_point(size = 5.0) +
   geom_errorbarh(aes(xmin = upper, xmax = lower))

Errorbar as a separate geom comes in distinct flavors: geom_errorbar is vertical and geom_errorbarh is horizontal; there are also things like geom_crossbar, geom_pointrange and the like. See ?geom_errorbar for help and some examples on all of them.