2014-01-20 91 views
9

在以下示例中,平均值和平均值是從原始數據計算出來的,並以barplot繪製。我想做同樣的事情,而不是使用barplot我想使用連接點。所以,我將不勝感激這麼多,如果任何人都可以告訴我怎麼...謝謝在ggplot2中使用stat_summary來計算平均值和sd,然後連接誤差棒的平均點

例如:

 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) 
+0

斯文:這是一個可再現的例子--- ToothGrowth是在鹼-R的數據集 - 感謝 – hema

+1

儘管如此,這將是比較明顯的,如果包括'數據(ToothGrowth)' 。 – ziggystar

回答

14

可以使用GEOM pointrange兩個點指示手段和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

+0

謝謝,這非常有幫助。我嘗試了很多想法來讓我的SD落後於平均值,而不使用單獨的DF,而這是最優雅的'ggplot' solutino。我用'geom =「ribbon」'也很好。 –