Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use stat_summary in ggplot2 to calculate the mean and sd, then connect mean points of error bars

Tags:

plot

r

ggplot2

In the following example, the Mean and se was calculated from the raw data and plotted in barplot. I want to do the same thing but instead of using barplot i want to use connected points. so, i will appreciate it so much if anyone can show me how...Thanks

example:

     data(ToothGrowth)

     ToothGrowth$F3 <- letters[1:2]
     # coerce dose to a factor
     ToothGrowth$dose <- factor(ToothGrowth$dose, levels = c(0.5,1,2))
     # facetting on the third factor
     ggplot(ToothGrowth, aes(y = len, x = supp )) + 
     stat_summary(fun.y = 'mean', fun.ymin = function(x) 0, geom = 'bar', 
     aes(fill =dose), position = 'dodge') +
     stat_summary(fun.ymin = function(x) mean(x) - sd(x), 
           fun.ymax = function(x) mean(x) + sd(x), position ='dodge', 
           geom = 'errorbar', aes(group = dose))+
    facet_wrap(~F3)   
like image 580
hema Avatar asked Jan 20 '14 16:01

hema


1 Answers

You can use the geom pointrange for both points indicating the means and errorbars.

ggplot(ToothGrowth, aes(y = len, x = supp, colour = dose, group = dose)) + 
  stat_summary(fun.y = mean,
               fun.ymin = function(x) mean(x) - sd(x), 
               fun.ymax = function(x) mean(x) + sd(x), 
               geom = "pointrange") +
  stat_summary(fun.y = mean,
               geom = "line") +
  facet_wrap( ~ F3)

enter image description here

like image 118
Sven Hohenstein Avatar answered Oct 13 '22 13:10

Sven Hohenstein